3

I want to customize back button to show some different text than the title of previous viewController.

I tried:

self.navigationItem.backBarButtonItem!.title = "CustomText"

in ViewDidLoad() method in relevant viewController.

I read here backBarButtonItem in iOS (Swift) that left bar button works here, but in my case it returns nil.

Thanks for help in advance!

Community
  • 1
  • 1
theDC
  • 6,364
  • 10
  • 56
  • 98

2 Answers2

3

The best place to do this title change is in its previous view controller'sviewDidDisappear method.

Ex: You want to see different title in ViewControllerB

ViewControllerA -> ViewControllerB.

In ViewControllerA's viewDidDisappear method,

override func viewDidDisappear(animated: Bool) {
            self.navigationItem.title = "ABC"
}

So when it will go to ViewControllerB, you will see "ABC" as back button title. When you come back to ViewControllerA, you should restore the old title in viewWillAppear method of ViewControllerA.

Amit89
  • 3,000
  • 1
  • 19
  • 27
3

I agree with @Amit89 but I suggest adding self.navigationItem.title = "CustomText" under viewWillDisappear like this:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    self.navigationItem.title = "CustomText"
}

Otherwise, your back button title will disappear suddenly after the new view controller push animation finished.

Also, remember to reset the old view controller's title when it appears.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationItem.title = "Original Title"
}
Wai Cheung
  • 71
  • 4
  • Both viewWillDisappear and viewDidDisappear will do the trick, it all depends on your requirement. – Amit89 May 07 '15 at 18:11
  • Both do their jobs, but viewWillDisappear is better in this case due to lack of lag in showing the new title. Thank you! However, I'm pretty curious what for is this backBarButtonItem if not for such purpose? – theDC May 07 '15 at 20:45
  • Now the challenge is how to avoid this lag which occurs when getting back to controller A – theDC May 07 '15 at 21:01