使用addTarget获取运行时异常:Action:forControlEvents

时间:2012-04-17 14:11:19

标签: iphone objective-c xcode ipad uibutton

我正在尝试使用 addTarget:Action:forControlEvents 但是我收到了一个无法识别的选择器的运行时异常。

这是从 initWithFrame 中的 UIView 子类调用的。 以下是我的代码:

myButton = [[UIButton alloc] initWithFrame:frame];
[myButton addTarget:self action:&selector(displayList:)
                         forControlEvents:UIControlEventTouchUpInside];

我的方法:

-(void)displayList:(id)sender

当我点击按钮时,它会收到以下消息:

-[MyClass displayList:]: unrecognized selector sent to instance. Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: -[MyClass displayList:]: unrecognized selector sent to instance.

MyClass 是一个自定义控件,它是一个带有 UIButton UILabel UIView 子类。这个类将放在另一个应用程序的ViewController上。

我不确定我错过了什么。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

应该阅读

[myButton addTarget:self action:@selector(displayList:) forControlEvents:UIControlEventTouchUpInside];

@而不是&

答案 1 :(得分:0)

[myButton addTarget:self action:&selector(displayList:) forControlEvents:UIControlEventTouchUpInside];

语法是@selector(displayList :)
此外,您的按钮可能无法触发事件。尝试以这种方式创建它:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //this will return an autoreleased UIButton object, be careful.
button.frame = CGRectMake(...);
...