I’m trying to write a convenience method that returns a UIButton and takes a title, CGRect and an action as parameters. My code compiles and runs, but crashes when I actually click the button.
Here is my convenience method:
+ (UIButton *)makeButton:(NSString *)title withRect:(CGRect)rect
withAction:(SEL)selectorX {
// setup button properties
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = rect;
[btn setFont:[UIFont boldSystemFontOfSize:20]];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[btn setBackgroundImage:[[UIImage imageNamed:@"btn_21.png"]
stretchableImageWithLeftCapWidth:10.0
topCapHeight:0.0] forState:UIControlStateNormal];
[btn setTitle:@"TEST" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(selectorX:)
forControlEvents:UIControlEventTouchUpInside];
return btn;
}
And here is how I’m calling it:
- (void)viewDidLoad {
[super viewDidLoad];
btn = [Utilities makeButton:@"TEST" withRect:CGRectMake(10, 100, 236, 45)
withAction:@selector(buttonActionTEST:)];
[self.view addSubview:btn];
}
- (void) buttonActionTEST:(id)sender {
[Utilities alert:@"yo yo yeoman"];
}
You need to provide both a target and a selector to call on that target. You’re only providing the selector, and then do this:
That’s wrong on two accounts: first, self in this context evaluates to the class
Utilities(not even an instance, but the Class object). And then, your attempt to provide the selector is also wrong as you pass a hardcoded selectorselectorX:and not the variable with the almost-same name. It should be done like this:and then you call it like this: