首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >添加新按钮时,旧按钮将消失

添加新按钮时,旧按钮将消失
EN

Stack Overflow用户
提问于 2011-11-26 00:58:15
回答 4查看 101关注 0票数 0

我有一个包含2个按钮的视图的iPhone应用程序。我在界面生成器中创建了这些按钮。

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

代码语言:javascript
复制
- (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中添加的另外两个按钮消失了。新的按钮非常小,只覆盖了视图的一小部分。

谁能告诉我我的扣子要放在哪里?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-11-26 01:03:23

为什么要分配另一个视图?它将替换旧的和它包含的所有内容。只需创建按钮即可。

票数 1
EN

Stack Overflow用户

发布于 2011-11-26 01:02:39

通过分配一个新视图self.view =,您将替换在界面构建器中设置的原始视图。注释掉第一行,您应该会发现原始视图(和按钮)仍然在那里,并添加了新按钮。

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

这是some example code of implementing loadView

票数 2
EN

Stack Overflow用户

发布于 2011-11-26 01:02:53

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

只需设置较大的框架,使您的新按钮较大- CGRectMake(100, 100, 100, 100)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8272144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档