Programmatically created UIBarButtonItem Not Launching Selector Action
Solution 1
The declaration of your button is missing something, namely the target
parameter. Try this:
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"+ Contact"
style:UIBarButtonItemStylePlain
target:self
action:@selector(showPicker:)];
[self.navigationItem setLeftBarButtonItem:item animated:YES];
This assumes that showPicker:
is in fact in the same class that's adding the button to the navigation item.
The target
parameter is the instance that should handle the event.
Solution 2
For those that are still having trouble with this, here is another solution that I have found: Instead of doing this:
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've added this UIBarButtonItem
in the toolbar in Storyboard. (Or you could just programmatically create your own UIBarButtonItem
before this set of code and add it to the items array of the UIToolbar.)
Somehow, ageektrapped's solution did not work for me, although his solution is what I would rather use. Maybe someone more knowledgeable about UIBarButtonItems could comment on why one solution worked over the other?
Solution 3
The "target" should be the object the selector belongs to, instead of nil.
Comments
-
ArtSabintsev about 4 years
Here is my
UIBarButton
:[self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"+ Contact" style:UIBarButtonItemStylePlain target:nil action:@selector(showPicker:)] animated:YES];
Here is the code it's supposed to launch:
- (void)showPicker:(id)sender { ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; picker.peoplePickerDelegate = self; [self presentModalViewController:picker animated:YES]; [picker release]; }
When I launch the app and click on the '+ Contact'
UIBarButton
, nothing happens. No errors, nada. I put in a breakpoint, and it never reaches the method referenced by the selector.Am I doing something wrong in the way I'm calling the selector?
Thanks!
-
ArtSabintsev almost 13 yearsYup, that fixed it! First time doing this programmatically. Thanks for fix!
-
ageektrapped almost 13 yearsDon't forget to mark this as the answer, then everybody wins! Thanks.
-
ArtSabintsev almost 13 yearsYup, all done now. I was going to do it earlier, but it wouldn't let me (i.e., had 9 mins left before I could do it...). Thanks for the quick response!