UIButtons を動的に生成するクラスがあり、セレクター アクションをメソッドと同じクラスに保持して、ジェネリックにしたいと考えています。ボタンをクリックするとクラッシュします。ベローは私のコードです
RB_RadioButton.h
#import <Foundation/Foundation.h>
@interface RB_RadioButton : NSObject {
NSMutableArray *options;
}
-(id)initWithOptions:(NSArray *)options;
-(void)renderRadioButtons:(UIView *)view initialXPos:(int)initialXPos initialYPos:(int)initialYPos height:(int)height width:(int)width spacing:(int)spacing;
@end
RB_RadioButton.m
#import "RB_RadioButton.h"
@implementation RB_RadioButton {
NSMutableArray *buttonArray;
}
-(id)initWithOptions:(NSArray *)optionsArray {
if(self = [super init]){
options = [[NSMutableArray alloc]initWithArray:optionsArray];
}
return self;
}
-(void)renderRadioButtons:(UIView *)view initialXPos:(int)initialXPos initialYPos:(int)initialYPos height:(int)height width:(int)width spacing:(int)spacing {
buttonArray = [[NSMutableArray alloc]init];
int xpos = initialXPos, ypos = initialYPos;
for (int i = 0; i < options.count; i++) {
UIButton *radio = [[UIButton alloc]initWithFrame:CGRectMake(xpos, ypos, height, width)];
radio.backgroundColor = [UIColor grayColor];
[radio setTag:i];
[radio addTarget:[RB_RadioButton class] action:@selector(actionTap) forControlEvents:UIControlEventTouchUpInside];
UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(xpos+30, ypos, height, width)];
l.text = [options objectAtIndex:i];
ypos = ypos + height + spacing;
[view addSubview:l];
[view addSubview:radio];
}
}
-(void)actionTap{
NSLog(@"lll");
}
@end
viewController.m
#import "RB_ViewController.h"
#import "RB_RadioButton.h"
@interface RB_ViewController ()
@end
@implementation RB_ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *arr = [[NSArray alloc]initWithObjects:@"a",@"b",@"c", nil];
RB_RadioButton *rd = [[RB_RadioButton alloc]initWithOptions:arr];
[rd renderRadioButtons:self.view initialXPos:20 initialYPos:20 height:20 width:20 spacing:10];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
上記のコードは、デバッグ コンソールにメッセージが表示されずにクラッシュします。
助けてください !
ありがとう