我在 ios 7 下使用 XCode 5 来做一个简单的项目。当我按下以编程方式创建的按钮时出现以下错误:
2013-11-10 09:16:02.969 Project2[446:70b] +[KNSunDynamicUIButton buttonSavePressed:]: unrecognized selector sent to class 0x221424
详细信息:
我创建了一个自定义方法,用于以编程方式创建 UIButton 对象。该自定义方法用于任何视图控制器。该自定义方法需要传入参数,如 x、y、宽度、高度、按钮标题和作为事件处理程序的选择器,并像“ (SEL)selector ”一样传入。
自定义方法(属于辅助类):
+(UIButton*)kNSunSetupWithSelector:(SEL)selector withX:(int)x y:(int)y width:(int)width height:(int)height
buttonTitle:(NSString*)buttonTitle backGroundColor:(CGColorRef) backGroundColor
{
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Save" forState:UIControlStateNormal];
button.frame = CGRectMake(x, y, width, height);
button.backgroundColor = [UIColor greenColor];
// selector is used over here
[button addTarget:self
action:selector
forControlEvents:UIControlEventTouchDown];
return button;
}
然后在视图控制器 .m 文件中,我调用该自定义方法,例如:
-(void)setUpButtons
{
SEL selector = @selector(buttonSavePressed:);
_buttonSave = [KNSunDynamicUIButton kNSunSetupWithSelector:selector withX:470 y:410 width:160 height:40 buttonTitle:@"Save" backGroundColor:(_buttonSaveColor)];
[self.view addSubview:_buttonSave];
}
@interface MyViewController ()
{
...
// buttons
UIButton* _buttonSave;
}
@end
并且在同一个视图控制器 .m 文件中定义按钮的事件处理程序,如:
- (void)buttonSavePressed:(UIButton*)button
{
NSLog(@"Button Save clicked.");
}
当我运行我的代码并点击按钮时,我看到了上面提到的异常。请帮忙谢谢。
PS如果我将自定义方法重写为签名中没有“(SEL)选择器”参数的替代方法,并让调用该自定义方法的控制器视图完成编码选择器的工作,那么也不例外:
-(void)setUpButtons
{
//Note: the codes are in my view controller .m file
_buttonSave = [KNSunDynamicUIButton kNSunSetupWithX:470 y:410 width:160 height:40 buttonTitle:@"Save" backGroundColor:_buttonSaveColor];
// Note: selector coding is taken care by codes of my view controller instead of by custom method
[_buttonSave addTarget:self
action:@selector(buttonSavePressed:)
forControlEvents:UIControlEventTouchDown];
[self.view addSubview:_buttonSave];
[_buttonSave setupView];
}
还有另一种自定义方法(我不喜欢该方法,因为它不处理动态传入的选择器):
+(UIButton*)kNSunSetupWithX:(int)x y:(int)y width:(int)width height:(int)height
buttonTitle:(NSString*)buttonTitle backGroundColor:(CGColorRef) backGroundColor
{
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Save" forState:UIControlStateNormal];
button.frame = CGRectMake(x, y, width, height);
button.backgroundColor = [UIColor greenColor];
return button;
}