Search code examples
iosobjective-cibaction

Programmatically add IBAction to UIButton


I am trying to add an action to a UIButton, but keep getting an exception:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '[UIImageView addTarget:action:forControlEvents:]: unrecognized selector sent to instance 0x595fba0'

Here is my code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *myIcon = [UIImage imageNamed:@"Icon_Profile"];
    self.profileButton = (UIButton*)[[UIImageView alloc] initWithImage:myIcon];

    [self.profileButton addTarget:self action:@selector(profileButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *buttonItem = [[[UIBarButtonItem alloc] initWithCustomView:profileButton] autorelease];

    NSArray *toolbarItems = [[NSArray alloc] initWithObjects:buttonItem, nil];

    [self setToolbarItems:toolbarItems animated:NO];

    //[toolbarItems release];
    //[profileButton release];
}

Then I have this method in the same View controller:

-(void)profileButtonPressed:(id)sender{

}

And in the header I have

-(IBAction)profileButtonPressed:(id)sender;

What's going on?


Solution

  • You can't cast a UIImageView object to UIButton and expect it to behave like a UIButton. Since you intend to create a UIBarButtonItem, use initWithImage:style:target:action: to init it with an image.

    UIBarButtonItem *buttonItem = [[[UIBarButtonItem alloc] initWithImage:myIcon style:UIBarButtonItemStylePlain target:self action:@selector(profileButtonPressed:)] autorelease]; 
    

    I think this is a better approach over creating a UIButton and assigning it as a custom view.