Search code examples
iosobjective-cuinavigationbarback-buttonuinavigationitem

Dynamically change NavigationBar Back Button Text from presented ViewController


I'm trying to change the back button text on a UINavigationBar upon receiving something from the network - basically replicating iMessage/FB Messenger by adding a new message count to the back button text ie. < Back (1) or < Messages (2)

I can change the back button text from the presented ViewController (in viewDidLoad)

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
barButton.title = @"Back";
self.navigationItem.backBarButtonItem = barButton;

But when I try to use that same code in another method that is called upon receiving a new message, the back button text doesn't change.

Any idea how I can change the back button text from the ViewController after it is presented?


Solution

  • First of all, UINavigationItem.backBarButtonItem for view controller A is not the left bar button when A is on top of the navigation stack, it is the left bar button when A is second-top of the navigation stack.

    That is to say, you push A, and then push B, when B is on top, the left bar button will be A.navigationItem.backBarButtonItem

    So a easy but not so elegant solution would be:

    Give B a weak reference to A, and A provide a interface to change it's back button like this:

    @implementation A
    -(void)changeBackTitle:(NSString*)title
    {
        UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStyleDone target:nil action:nil];
        self.navigationItem.backBarButtonItem = back;
    }
    -(void)restoreBackButton
    {
        self.navigationItem.backBarButtonItem = nil;
    }
    @end
    

    Then B call this method to change the back button title when B is on top of the stack

    Remember to restore the back Button when B is popped, otherwise next time push B from A will show a maybe wrong back button.