按钮@selector如果在NSObject中定义按钮则不起作用

时间:2014-02-13 21:38:42

标签: ios objective-c xcode uibutton nsobject

我有以下问题:我试图在NSObject中定义一个按钮(在一个单独的文件中)并将其添加到我的ViewController中:

NSObject方法:

在obj.h中:

+(void)NewButtonInView:(UIView *)view withAction:(SEL)actionbutton;

在obj.m

+(void)NewButtonInView:(UIView *)view withAction:(SEL)actionbutton {

 UIButton *button = [[UIButton alloc] init];
 button.frame = CGRectMake(0, 0, 50, 50);
 [button addTarget:self action:actionbutton forControlEvents:UIControlEventTouchUpInside];
}

在我的ViewCotroller中我导入了obj.h和:

[obj NewButtonInView:[self view] withAction:@selector(actionB:)];

-(void)actionB:(UIButton *)button {
 //some code
}

按钮看起来很好但是当我点击它时我收到以下错误: " [obj actionB:]:无法识别的选择器发送到班级"

感谢任何帮助。 谢谢。

2 个答案:

答案 0 :(得分:5)

问题在于这一行

[button addTarget:self action:actionbutton forControlEvents:UIControlEventTouchUpInside];

具体来说,使用self。您将actionB:方法放在viewController中,但因为NewButtonInView:withAction:方法属于obj类方法,所以self引用类obj。要修复它,请在视图控制器中作为方法的参数传递,如此

+(void)NewButtonInView:(UIView *)view withAction:(SEL)actionbutton target: (id) target {

UIButton *button = [[UIButton alloc] init];
button.frame = CGRectMake(0, 0, 50, 50);
[button addTarget: target action:actionbutton forControlEvents:UIControlEventTouchUpInside];
}

答案 1 :(得分:0)

尝试使用返回值定义它,如下所示:

+(UIButton *)NewButtonInView:(UIView *)view withAction:(SEL)actionbutton withTarget:(id)target{

 UIButton *button = [[UIButton alloc] init];
 button.frame = CGRectMake(0, 0, 50, 50);
 [button addTarget:target action:actionbutton forControlEvents:UIControlEventTouchUpInside];
 return button;
}

然后当你打电话时:

UIButton *button = [obj NewButtonInView:[self view] withAction:@selector(actionB:) withTarget:self];

不确定你为什么要在NSObject中而不是在你的视图控制器中这样做,但如果你这样做的话就是这样做的。