我有一个包含2个按钮的视图的iPhone应用程序。我在界面生成器中创建了这些按钮。
现在,我想以编程方式向视图中添加一个新按钮:
- (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中添加的另外两个按钮消失了。新的按钮非常小,只覆盖了视图的一小部分。
谁能告诉我我的扣子要放在哪里?
发布于 2011-11-26 01:03:23
为什么要分配另一个视图?它将替换旧的和它包含的所有内容。只需创建按钮即可。
发布于 2011-11-26 01:02:39
通过分配一个新视图self.view =,您将替换在界面构建器中设置的原始视图。注释掉第一行,您应该会发现原始视图(和按钮)仍然在那里,并添加了新按钮。
如果您确实希望以编程方式创建视图,正确的方法是实现loadView方法,并在其中为self.view分配一个新的UIView。(显然,您希望将UI项添加到该视图中。)仔细阅读UIViewController文档是值得的。
这是some example code of implementing loadView。
发布于 2011-11-26 01:02:53
删除第一行中的两行并查看结果。没有理由为viewConrtoller创建新的整个视图。
只需设置较大的框架,使您的新按钮较大- CGRectMake(100, 100, 100, 100);
https://stackoverflow.com/questions/8272144
复制相似问题