Question

I have the following problem: I am trying to define a button in an NSObject (in a separate file) and add it to my ViewController:

NSObject method:

in obj.h:

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

in 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];
}

in my ViewCotroller I import the obj.h and:

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

and:

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

The button looks fine but when I click it I get the following error: "[obj actionB:]: unrecognized selector sent to class"

Any help is appreciated. Thank you.

Was it helpful?

Solution

the problem is this line

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

specifically, the use of self. You put the actionB: method in the viewController, but because the NewButtonInView:withAction: method is in a class method of obj self refers to the class obj. To fix it pass in the view controller as a parameter to the method like this

+(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];
}

OTHER TIPS

Try defining it with a return value, as follows:

+(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;
}

Then when you call it:

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

Not sure why you're doing it in an NSObject instead of in your view controller, but that's the way to go about it if you do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top