xcode iPhone Dev - 手动创建 UIButton
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1210408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iPhone Dev - Create UIButton Manually
提问by mk12
I'm learning how to develop on the iPhone, I bought a book called Beginning iPhone 3 development Exploring the SDK. After I bit I decided to ditch Interface Builder. I still design all my views in IB, but I write It all in code and only use the nib file to get the controls' frames.
我正在学习如何在 iPhone 上进行开发,我买了一本名为 Beginning iPhone 3 development Exploring the SDK 的书。在我咬了一口之后,我决定放弃 Interface Builder。我仍然在 IB 中设计我的所有视图,但我全部用代码编写并且只使用 nib 文件来获取控件的框架。
So now I need to make a UIButton
, and the documentation is different from the other controls. I tried using initWithFrame:
, and theres this other method buttonWithType:
which I assume is autoreleased, but anyway I couldn't get a button to appear on the screen. Could someone please write a bit of code that locally creates a button with a title I can change that I can then just add to my views subview and release so I can see how it's done?
所以现在我需要制作一个UIButton
,并且文档与其他控件不同。我尝试使用initWithFrame:
,还有另一种buttonWithType:
我认为是自动发布的方法,但无论如何我无法让按钮出现在屏幕上。有人可以写一些代码,在本地创建一个带有标题的按钮,我可以更改它,然后我可以将其添加到我的视图子视图并发布,以便我可以看到它是如何完成的?
回答by Thomas Müller
I'd try something like this:
我会尝试这样的事情:
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];
Disclaimer: Just typing this in here. I don't have access to my Mac at the moment so I can't test it.
免责声明:只需在此处输入即可。我目前无法访问我的 Mac,因此无法对其进行测试。
P.S. Any particular reason not to use Interface Builder? Just curious.
PS 有什么特别的理由不使用 Interface Builder?只是好奇。