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

编程入门 行业动态 更新时间:2024-10-27 10:24:45
本文介绍了如何以编程方式为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?

本文发布于:2023-07-27 05:23:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1220588.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方式   UIButton   Call

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!