我正在尝试从控制器中构造一些视图代码(显然没有使用nib)。因此,我尝试了一个简单的例子,但由于某种原因,我无法将目标添加到控制器中的按钮,其余的很好。这是我正在尝试的:
或者Controller.h:
#import <UIKit/UIKit.h>
#import "IndexView.h"
@interface IndexController : UIViewController
{
}
@property (nonatomic) IndexView *contentView;
@end
Controller.m或者
#import "IndexController.h"
#import "IndexView.h"
@interface IndexController ()
@end
@implementation IndexController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.contentView = [[IndexView alloc]init];
[self.view addSubview:self.contentView];
[self connectUIElements];
}
return self;
}
- (void) connectUIElements
{
[self.contentView.testButton addTarget:self action:@selector(testButtonClicked) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark --
#pragma mark UIHandler
- (void) testButtonClicked
{
NSLog(@"testbutton clicked");
}
@end
View.h
#import <UIKit/UIKit.h>
@interface IndexView : UIView
@property (nonatomic, strong) UIButton *testButton;
@end
View.m
#import "IndexView.h"
@implementation IndexView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setUpView];
}
return self;
}
- (id) init
{
self = [super init];
if (self) {
[self setUpView];
}
return self;
}
- (void) setUpView
{
[self setBackgroundColor:[UIColor whiteColor]];
self.testButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 50, 100, 50)];
self.testButton.backgroundColor = [UIColor greenColor];
[self.testButton setTitle:@"hello, world" forState:UIControlStateNormal];
[self addSubview:self.testButton];
}
@end
我正在探索更接近经典MVC模式的可能性,以及距苹果中介解释更远的地方。知道什么是错的吗?
答案 0 :(得分:0)
您必须使用initWithFrame:
创建视图,UIView
是init
的默认初始值设定项。 (原因不适用于简单的{{1}} - 但我猜这里! - 可能是视图大小为零,因此触摸事件不起作用。)