ahmad
ahmad

Reputation: 1252

UIButton target not recognized when adding button superview controller to another viewController

I created a sub-class of UIViewController called toolbarViewController , I declare a UIButton in this view controller and specified it's target as following

UIButton *button = [[UIButton alloc]initWithFrame:myFrame];
[button addTarget:self action:@selector(doSomething) forContorlEvents:UIControlEventTouchUpInside];

then i do the following in a different view controller

toolbarViewController *toolbar = [[toolbarViewController alloc]init];
[self.view addSubview:toolbar.view];

the problem is that when i press the button i get the exception: Unrecognized selector ( doSomething ) send to instance , what am i doing wrong here ?

doSomething declaration in toolbarViewController.h

-(void)doSomething;

and in toolbarViewController.m

-(void)doSomething{ NSLog("doSomething got called"); }

Upvotes: 0

Views: 935

Answers (3)

Gui Moura
Gui Moura

Reputation: 1360

One possible case is if you add a UITapGestureRecognizer to the UIButton's superview. On iOS5 it seems there is an issue with UITapGestureRecognizers that do not cancel the tap in view.

So all you need to do is set the

tapGesture.cancelsTouchesInView = NO;

let me know if it helped!

Upvotes: 0

Peter Zhu
Peter Zhu

Reputation: 51

if you use ARC,you alloc toolbarViewController,but it has relese。you can try to this:

ViewController.h
@interface ViewController : UIViewController{
    toolbarViewController * toolbar;
}
@property(nonatomic,strong) toolbarViewController * toolbar;


ViewController.m
@synthesize toolbar = _toolbar;


    toolbar = [[toolbarViewController alloc]initWithNibName:@"toolbarViewController" bundle:[NSBundle mainBundle]];

and you alloc button can do this:

UIButton *bt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        bt.frame = myFrame;
        [bt addTarget:self action:@selector(dosomething) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:bt];

Upvotes: 1

Abdullah Md. Zubair
Abdullah Md. Zubair

Reputation: 3324

Check the declaration of doSomething. If you declare IBAction something like -(IBAction)doSomething:(id)sender, you should add selector like

[button addTarget:self action:@selector(doSomething:) forContorlEvents:UIControlEventTouchUpInside];

instead of

[button addTarget:self action:@selector(doSomething) forContorlEvents:UIControlEventTouchUpInside];

Upvotes: 1

Related Questions