iPhone Dev - 手动创建UIButton

mk1*_*k12 30 iphone xcode uibutton

我正在学习如何在iPhone上开发,我买了一本名为Beginning iPhone 3开发探索SDK的书.在我咬了之后我决定抛弃Interface Builder.我仍然在IB中设计我的所有视图,但是我在代码中编写了所有视图,并且只使用nib文件来获取控件的帧.

所以现在我需要制作一个UIButton,并且文档与其他控件不同.我尝试使用initWithFrame:,并且buttonWithType:我认为这个其他方法是自动释放的,但无论如何我无法在屏幕上显示按钮.有人可以写一些代码,在本地创建一个标题我可以更改的按钮,然后我可以添加到我的视图子视图和发布所以我可以看到它是如何完成的?

Tho*_*ler 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];
Run Code Online (Sandbox Code Playgroud)

免责声明:只需在此输入.我目前无法访问我的Mac,所以我无法测试它.

PS任何特殊原因不使用Interface Builder?只是好奇.

  • 我不喜欢IB,因为它就像一个大黑盒子,我看不出发生了什么,只是让事情变得复杂......我认为它唯一有用的就是设计界面.这是myButton自动释放的吗?如果我做了UIButton*myButton = [[UIButton alloc] initWithFrame:...],它会工作吗?..但是我如何设置只读按钮类型.. (7认同)
  • @ Mk12,查看[UIButton alloc initWithFrame:frame vs. UIButton buttonWithType]的答案(http://stackoverflow.com/questions/6245882/uibutton-alloc-initwithframeframe-vs-uibutton-buttonwithtype/6245883#6245883). (2认同)