【问题标题】:Programmatically add a UIButton to a Storyboard View以编程方式将 UIButton 添加到 Storyboard 视图
【发布时间】:2012-08-17 09:15:35
【问题描述】:

我有一个 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]; 

}

【问题讨论】:

    标签: iphone ios ios4 storyboard


    【解决方案1】:

    将按钮放在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 中显示它。

    【讨论】:

    • 我只是在 viewDidLoad 上调用 initLoginForm,然后在 initLoginForm 中将它添加到视图中,希望没问题
    • 没关系。还是崩溃了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    相关资源
    最近更新 更多