如何以编程方式为UIButton设置Call​​Back?

时间:2012-06-24 04:00:13

标签: objective-c cocoa-touch

手工制作:

[btnRun addTarget:self action:@selector(RunApp:) forControlEvents:UIControlEventTouchUpOutside];

以编程方式构建:以下内容如??

- (void) setRunButton:(UIButton*)objectName mySelector:(NSString*)funcName myControlEvent:(NSString*) controlEvent
{
    [objectName addTarget:self action:@selector(funcName) forControlEvents:controlEvent];
}

2 个答案:

答案 0 :(得分:3)

我认为您需要以下内容:

- (void)setRunButton:(UIButton *)objectName mySelector:(NSString *)action myControlEvent:(UIControlEvents)controlEvent {

   [objectName addTarget:self action:NSSelectorFromString(action) forControlEvents:controlEvent];

}

将选择器作为NSString传递是很常见的,但您可以使用NSSelectorFromString()将选择器的字符串名称转换为选择器。

控件事件参数不是字符串,因此我将myControlEvent参数更改为UIControlEvents类型。

使用@selector(action)将选择器传递给方法更为常见。但是,@selector在编译时处理,因此参数实际上不是NSString。在这种情况下,该方法将如下所示:

- (void)setRunButton:(UIButton *)objectName mySelector:(SEL)action myControlEvent:(UIControlEvents)controlEvent {

   [objectName addTarget:self action:action forControlEvents:controlEvent];

}

答案 1 :(得分:1)

将整个选择器作为参数传递

- (void) setRunButton:(UIButton*)objectName mySelector:(SEL)action myControlEvent:(NSString*) controlEvent
{
    [objectName addTarget:self action:action forControlEvents:controlEvent];
}