以编程方式将UIButton添加到Storyboard视图

时间:2012-08-17 01:09:32

标签: iphone ios ios4 storyboard

我有一个Storyboard View Controller(带有我自己的自定义子类),我有一个initWithCoder自定义方法,我希望用我自己的自定义对象来欢迎视图(我想保持以编程方式执行此操作的灵活性。

代码在调用[self.view addSubview:button];之前正常工作,然后崩溃:“无法在捆绑中加载NIB”。

我想要做的就是在我的视图中添加一个UIButton ......

- (id)initWithCoder:(NSCoder*)aDecoder 
{
    if(self = [super initWithCoder:aDecoder]) 
    {
        [self initLoginForm];
    }
    return self;
}

-(void)initLoginForm
{

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 170, 100, 30);
    [button setTitle:@"Login..." forState:UIControlStateNormal];
    [button addTarget:self action:@selector(handleLoginAttempt) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button]; 

}

1 个答案:

答案 0 :(得分:2)

如何将按钮放在viewDidLoad方法中,然后将其添加到initLoginForm

这样的事情:

-(void)viewDidLoad {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 170, 100, 30);
    [button setTitle:@"Login..." forState:UIControlStateNormal];
    [button addTarget:self action:@selector(handleLoginAttempt) forControlEvents:UIControlEventTouchUpInside];
}

-(void)initLoginForm {

[self.view addSubview:button];

}

或将其添加到viewDidLoad然后将其隐藏,然后在initLoginForm中显示。