开发者

Programmatically created UIBarButtonItem Not Launching Selector Action

开发者 https://www.devze.com 2023-03-19 14:06 出处:网络
Here is my UIBarButton: [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@\"+ Contact\"

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 su开发者_如何学Pythonpposed 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!


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.


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?


The "target" should be the object the selector belongs to, instead of nil.

0

精彩评论

暂无评论...
验证码 换一张
取 消