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";
}
else{
//Do your stuff;
self.navigationItem.rightBarButtonItem.title = @"Edit";
}
}
That is all you need to do. Try it out. Hope it helps someone out there.