我从界面构建器创建了三个按钮并链接到它:
@property (strong, nonatomic) IBOutlet UIButton *btn1;
@property (strong, nonatomic) IBOutlet UIButton *btn2;
@property (strong, nonatomic) IBOutlet UIButton *btn3;
现在我将它们加载到这样的数组中:
NSArray *array=[[NSArray alloc]initWithObjects:btn1,btn2,btn3, nil];
现在出于某种原因,我想将所有这些链接到同一个选择器并尝试这个:
for(UIButton *myButton in array)
{
[myButton addTarget:self action:@selector(onBtnPress:) forControlEvents:UIControlEventTouchUpInside];
}
将选择器定义为:
-(void)onBtnPress:(id)sender
{
NSLog(@"PRESSED");
}
但它不起作用并抛出此错误:
修改
如果我在同一个链接按钮的viewController上执行此操作,则它可以正常工作。但是,如果我将按钮传递给另一个类并执行此操作则会抛出错误。
我将它传递给另一个类,如下所示:
在viewController中:
RadioButton *radioSet=[[RadioButton alloc]initWithButtons:@[btn1,btn2,btn3]];
在单选按钮类中:
@interface RadioButton()
@property(nonatomic,strong)NSMutableArray *inactiveBtn;
@end
@implementation RadioButton
- (instancetype)initWithButtons:(NSArray *)buttons
{
self = [super init];
if (self) {
self.initialBtnList=[[NSMutableArray alloc]initWithArray:buttons];
[self initialState];
}
return self;
}
-(void)initialState
{
for(UIButton *myButton in initialBtnList)
{
[myButton addTarget:self action:@selector(onBtnPress:) forControlEvents:UIControlEventTouchUpInside];
}
}