[英]Objective-C : Call a method from another class in addTarget:action:forControlEvents
Here is my problem : 这是我的问题:
I want to assign an Event on an UIButton. 我想在UIButton上分配一个事件。 I use this method :
我用这个方法:
- (void)addTarget:(id)target
action:(SEL)action
forControlEvents:(UIControlEvents)controlEvents
like this : 像这样 :
[newsButton addTarget:self
action:@selector(myEvent2)
forControlEvents:UIControlEventTouchUpInside];
newsButton is my UIButton. newsButton是我的UIButton。
If myEvent2 belongs to the class where I am, the code is compiling and executing fine, everybody is happy. 如果myEvent2属于我所在的类,代码正在编译并执行正常,每个人都很高兴。
But if myEvent2 belongs to another class I don't succeed to execute it (the project compiles fine). 但是如果myEvent2属于另一个类,我就没有成功执行它(项目编译得很好)。
I tried out to change my code in that way : 我尝试以这种方式更改我的代码:
MyViewController* test = [[MyViewController alloc] init];
[newsButton addTarget:self
action:@selector([test myEvent2])
forControlEvents:UIControlEventTouchUpInside];
but I get the followings errors : 但我得到以下错误:
Expected ':' before '[' token
在'''令牌之前预期':'
Method name missing in @selector
@selector中缺少方法名称
Does someone have any solution to my problem ? 有人对我的问题有任何解决方案吗?
Thanks by advance :) 先谢谢:)
您需要将addTarget:self
更改为addTarget:test
MyViewController* test = [[MyViewController alloc] init];
[newsButton addTarget:test
action:@selector(myEvent2)
forControlEvents:UIControlEventTouchUpInside];
Another option is to use a redirection method: 另一种选择是使用重定向方法:
- (void)myRedirectHandler {
[ test myEvent2 ];
}
... ...
[newsButton addTarget:self
action:@selector(myRedirectHandler)
forControlEvents:UIControlEventTouchUpInside];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.