Sunday, February 13, 2011

Change text and action of UIBarButtonItem

To change the text and the action of a UIBarButtonItem is no straightforward thing.

1. In Interface Builder, make sure the UIBarButtonItem is of Identifier: Custom

2. Do the usual hooking up of the button via an IBOutlet.

3. Use this code (where 'myBarButtonItem' is the existing button that has already been hooked up via an IBOutlet, and 'doSomeNewAction' is the new action I wish for the button to perform):

UIBarButtonItem *myNEWBarButtonItem = self.myBarButtonItem;
[myNEWBarButtonItem setTarget:self];
[myNEWBarButtonItem setTitle:@"Do Some New Action"];
[myNEWBarButtonItem setAction:@selector(doSomeNewAction:)];

2 comments:

  1. Anonymous9:03 AM

    create a new button and replace your old BarButtonItem, it could be as following

    UIBarButtonItem *newButton = [[UIBarButtonItem alloc] initWithTitle:@"Do Some New Action" target:self action:@selector(doSomeNewAction:)];
    self.navigationItem.leftBarButtonItem = newButton;

    ReplyDelete
  2. somewhere along the road, i tried the create new button and replace the old one method but it didn't work for me. maybe i was doing something wrong (as always).

    ReplyDelete