MJQZ1347 MJQZ1347 - 3 months ago 18
Swift Question

How to change Back button text from within the child view controller?

I know that you can set the title of the back button from the IB or in

prepareForSegue
, but in my app I need to update the title according to events that can happen while the controller is visible.

I tried but nothing happens:

self.navigationItem.backBarButtonItem = UIBarButtonItem(title: title, style: .Plain, target: nil, action: nil)


This works though but has no back arrow:

self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title, style: .Plain, target: nil, action: "popVC")


Any ideas?

Answer

The backBarButtonItem is the item used for the back button of the next controller in the navigation stack.
So for example if you have a navigation controller with a root viewController A and you push a viewController B, then the back button title that you see once B is pushed is configured using A.

You could have something like this :

A.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Go back to A", style: .Plain, target: nil, action: nil)

Once B is pushed, you see a back button with "Go back to A".

In your case the tricky part is to find A in the navigation stack from B. You can do it by searching in the viewControllers of the navigationController like so :

// This code works from the `B` view controller
let viewControllers = self.navigationController?.viewControllers ?? []
if let indexOfCurrent = viewControllers.indexOf(self) where (indexOfCurrent > viewControllers.startIndex) {
    let indexOfPrevious = indexOfCurrent.advancedBy(-1)
    let previousViewController = viewControllers[indexOfPrevious]
    previousViewController.navigationItem.backBarButtonItem?.title = "New Title"
}

Edit

I don't know any clean way to refresh the navigation bar after that. Maybe you could ask a separate question just for that.
What you could do is pop and push the view controller without animation

if let navigationController = self.navigationController {
    navigationController.popViewControllerAnimated(false)
    navigationController.pushViewController(self, animated: false)
}

Or maybe try to create a new UIBarButtonItem instead of changing the title of the existing one.

Comments