0

我正在尝试从控制器中构造一些视图代码(显然不使用笔尖)。因此,我尝试了一个简单的示例,但由于某种原因,我无法将目标添加到控制器中的按钮,休息就可以了。这是我正在尝试的:

控制器.h:

#import <UIKit/UIKit.h>
#import "IndexView.h"

@interface IndexController : UIViewController
{

}

@property (nonatomic) IndexView *contentView;

@end

控制器.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

查看.h

#import <UIKit/UIKit.h>

@interface IndexView : UIView

@property (nonatomic, strong) UIButton *testButton;

@end

查看.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 模式并远离 Apple 中介解释的可能性。知道有什么问题吗?

4

1 回答 1

0

您必须使用 . 创建视图initWithFrame:,这是UIView. (原因很简单init- 但我猜在这里! - 可能是视图大小为零,因此触摸事件不起作用。)

于 2013-05-23T20:59:15.650 回答