Programmatically created UIBarButtonItem action does not start selector

Here is my UIBarButton :

 [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"+ Contact" style:UIBarButtonItemStylePlain target:nil action:@selector(showPicker:)] animated:YES]; 

Here is the code that it should run:

 - (void)showPicker:(id)sender { ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; picker.peoplePickerDelegate = self; [self presentModalViewController:picker animated:YES]; [picker release]; } 

When I launch the application and click "+ Contact" UIBarButton , nothing happens. No mistakes, nada. I set a breakpoint and it never reaches the method referenced by the selector.

Am I doing something wrong in what I call a selector?

Thanks!

+8
ios objective-c xcode uinavigationcontroller uibarbuttonitem
source share
3 answers

There is something missing in the declaration of your button, namely the target parameter. Try the following:

 UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"+ Contact" style:UIBarButtonItemStylePlain target:self action:@selector(showPicker:)]; [self.navigationItem setLeftBarButtonItem:item animated:YES]; 

This assumes that showPicker: actually in the same class that adds the button to the navigation item.

The target parameter is the instance that should handle the event.

+23
source share

For those who still have problems with this, here is another solution I found: Instead:

 self.myBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Woot Woot" style:UIBarButtonItemStyleBordered target:self action:@selector(performActionForButton)]; 

Try something like this:

 NSArray *barButtons = [self.myToolbar items]; UIBarButtonItem *myBarButton = [barButtons objectAtIndex:0]; [myBarButton setAction:@selector(performActionForButton)]; 

* Make sure you add this UIBarButtonItem to the toolbar in the Storyboard. (Or you can just programmatically create your own UIBarButtonItem before this set of code and add it to the items array of UIToolbar.)

Somehow, the ageektrapped solution did not work for me, although its solution is what I would prefer to use. Maybe someone more knowledgeable about UIBarButtonItems can comment on why one solution worked on another?

+3
source share

"target" must be the object to which the selector belongs, instead of nil.

+2
source share

All Articles