繁体   English   中英

当我添加新按钮时,旧按钮消失

[英]Old buttons disappear when I add a new one

我有一个包含2个按钮的iPhone App。 我在界面生成器中创建了这些按钮。

现在,我要以编程方式向视图添加一个新按钮:

- (void) addButton {
    //allocate the view
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    //set the view's background color
    self.view.backgroundColor = [UIColor whiteColor];

    //create the button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    //set the position of the button
    //button.frame = CGRectMake(100, 10, 50,50);
    button.frame = CGRectMake(100, 100, 10,10);

    //set the button's title
    [button setTitle:@"Click Me!" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(myButtonClick:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];

    //add the button to the view
    [self.view addSubview:button];  
}

完成,它可以工作,但是在Interface Builder中添加的其他2个按钮已经消失了。 新按钮非常小,仅覆盖一小部分视图。

谁能告诉我我的按钮要去哪里?

通过分配新视图self.view = -您将替换在界面构建器中设置的原始视图。 注释掉第一行,您应该找到原始视图(和按钮),并添加新按钮。

如果确实要以编程方式创建视图,则执行此操作的正确方法是实现loadView方法并在其中为self.view分配一个新的UIView。 (显然,您想向该视图添加UI项。)值得仔细阅读UIViewController文档。

这是一些实现loadView的示例代码

删除前两行并查看结果。 没有理由为viewConrtoller创建新的整个视图。

只需将框架设置为更大,以使新按钮变大CGRectMake(100, 100, 100, 100) ;

为什么要分配另一个视图? 它将取代旧的旧文件及其包含的所有内容。 只需创建按钮即可。

像这样:

UIButton* Button = [UIButton buttonWithType: UIButtonRoundedRect];
[Button setTitle:@"MyButton" forState:UIControlNormal];
Button.frame = CGRectMake(100, 100, 200, 30);
[Button addTarget:self action:@selector(myButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[[self view] addSubview: Button];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM