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

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

本文介绍了如何以编程方式为UIButton设置Call​​Back?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

手动构建:

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






程序化构建:


Programmatically built: something of the following like ??

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


推荐答案

像下面这样:

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

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

}

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

It is unusual to pass a selector as an NSString but you can use NSSelectorFromString() to convert the string name of the selector into a selector.

控制事件参数不是它们是枚举的字符串,所以我改变了 myControlEvent 参数, c $ c> UIControlEvents 类型。

Control events parameters are not strings they are an enumeration so I have changed the myControlEvent parameter to have the UIControlEvents type.

这将是更通常的选择器传递到方法使用 @selector (action)。但是, @selector 在编译时处理,因此参数实际上不是 NSString 。在这种情况下,方法看起来像:

It would be more usual to pass the selector to the method using @selector(action). However, @selector is handled at compile time so the parameter isn't actually an NSString. In this case the method would look like:

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

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

}

这篇关于如何以编程方式为UIButton设置Call​​Back?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:59