在哪里插入以编程方式创建按钮的代码?

时间:2011-04-18 14:40:05

标签: iphone button

我从网上收到一些JSON,根据这些数据,我必须创建2或3个按钮。我的部分gui是静态的并且在NIB中创建(不会改变),只有按钮的数量会改变。我在代码中找到了用于制作按钮的代码:

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

 //set the position of the button
 button.frame = CGRectMake(100, 170, 100, 30);
 //set the button's title
 [button setTitle:@"Click Me!" forState:UIControlStateNormal];

这是正确的方法吗?我应该在我的viewcontroller的哪个方法中放入这段代码?

2 个答案:

答案 0 :(得分:1)

只要视图已经加载,您就可以随时添加按钮。您需要添加到上述代码中的一件事是

[[self view] addSubview:button];

使用此代码,屏幕上有一个按钮,但它无法触发任何操作。您可能还想添加:

[button addTarget:self action:@selector(someMethod:) forControlState:UIControlEventTouchUpInside];

答案 1 :(得分:0)

您应该在委托/方法中添加解析JSON数据的按钮。 不要忘记将创建的按钮添加到视图中:

[containerView addSubview:button];