iPhone – Set or change title of UIBarButtonItem

Now this is very trivial and does not need a lot of work. I had googled for this but got some not so good answers so I tried out something and it works fine.

So basically what we are trying to achieve here is:

1) First create a UIBarButtonItem and put it in navigation.

2) Changing the title of the BarButtonItem on tap.

We do this by first declaring the button (in this case, the title is ‘Edit’) and attach a function to it which basically does something and also changes the Button Label to ‘Done’.

So lets first add the button on view load:

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(alterMode) ];

So the action ‘alterMode’ is now attached with the rightBarButtonItem. Now we just need our altermode method to change the title of the button and we are done.

-(void) alterMode {
  if(self.navigationItem.rightBarButtonItem.title == @"Edit") {
    //Do your stuff;
    self.navigationItem.rightBarButtonItem.title = @"Done";
    //Do your stuff;
    self.navigationItem.rightBarButtonItem.title = @"Edit";

That is all you need to do. Try it out. Hope it helps someone out there.


4 thoughts on “iPhone – Set or change title of UIBarButtonItem

  1. Randal is right you need, if([self.editButton.title isEqualToString:@”Edit”])

    Other than that, it works a treat.

    Found lots of other solutions, but they all required many lines of code.

    This solution follows the “KISS” principle.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s