xcode 以编程方式生成 UIButton 并将它们与 IBAction 关联
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2370031/
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
Programmatically generating UIButtons and associate those with IBAction
提问by Nicsoft
How do I do if I want to programatically generate a set of buttons and then associate those with IBActions? It's easy if I add the buttons in Interface Builder, but that I cannot do for this case.
如果我想以编程方式生成一组按钮,然后将它们与 IBActions 相关联,我该怎么办?如果我在 Interface Builder 中添加按钮很容易,但在这种情况下我不能这样做。
回答by mrueg
The buttons have the method - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
.
按钮有方法- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
。
The code to use this would look like this:
使用它的代码如下所示:
UIButton *myButton = [[UIButton alloc] init...];
[myButton addTarget:something action:@selector(myAction) forControlEvents:UIControlEventTouchUpInside];
This assumes that your IBAction is named myAction
and that something
is the controller for which that action is defined.
这假设您的 IBAction 已命名myAction
并且something
是为其定义该操作的控制器。
回答by Macmade
First, create the button:
首先,创建按钮:
UIButton * btn;
btn = [ [ UIButton alloc ] initWithFrame: CGRectMake( 0, 0, 200, 50 ) ];
Then adds an action:
然后添加一个动作:
[ btn addTarget: self action: @selector( myMethod ) forControlEvents: UIControlEventTouchDown ];
Then adds the button to a view:
然后将按钮添加到视图中:
[ someView addSubView: btn ];
[ btn release ];