iPhone开发 - 手动创建UIButton

30

我正在学习如何在iPhone上开发应用,我购买了一本名为《Beginning iPhone 3 development Exploring the SDK》的书。不久之后,我决定放弃Interface Builder。我仍然在IB中设计所有的视图,但是我用代码编写所有内容,并且只使用nib文件来获取控件的框架。

现在我需要创建一个UIButton,而文档与其他控件不同。我尝试使用initWithFrame:,还有另外一个方法buttonWithType:,我认为这个方法是自动释放的,但是无论如何我都无法在屏幕上显示出按钮。请问能否提供一些本地创建带有更改标题的按钮的代码,以便我可以将其添加到我的视图子视图并进行释放,以便了解如何完成它?

1个回答

83

我会尝试这样做:

    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    myButton.frame = CGRectMake(20, 20, 200, 44); // position in the parent view and set the size of the button
    [myButton setTitle:@"Click Me!" forState:UIControlStateNormal];
    // add targets and actions
    [myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // add to a view
    [superView addSubview:myButton];

免责声明:只是在这里打字。目前无法访问我的Mac电脑,因此无法进行测试。

P.S. 没有使用Interface Builder的特别原因吗?只是好奇。


1
假设选择器 buttonClicked: 存在,这是完全有效且良好的方法。+1 - Tim
7
我不喜欢IB(Interface Builder)因为它像一个巨大的黑匣子,我无法看到发生了什么,只会让事情变得更加复杂... 我认为唯一有用的是设计界面。这个myButton是否被自动释放了?如果我使用以下代码行 UIButton *myButton = [[UIButton alloc] initWithFrame:...]; 它还能正常工作吗?但是这样我该如何设置只读的按钮类型? - mk12
buttonType是只读属性。我不确定如果使用initWithFrame:你会得到什么类型的按钮,而且以后也无法更改它。你可以尝试一下并查看buttonType属性是什么,但使用buttonWithType:可能更安全。是的,这个按钮将被自动释放。关于设置myButton.titleLabel.text,我不确定。如果以后要为不同状态添加不同的标题,我猜你需要修改代码。我只会使用myButton.titleLabel来修改按钮的样式,如颜色、字体和字号。 - Thomas Müller
2
@Mk12,看看这个关于UIButton alloc initWithFrame:frame vs. UIButton buttonWithType的答案。 - ma11hew28
动作选择器可以选择以下形式:
  • (void) buttonClicked:(id)sender forEvent:(UIEvent *)event
- combinatorial
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接