I had a parent view controller with a really long title. This resulted in the back button text bleeding into the title of the child view controller.
After trying a bunch of different solutions, this is what I ended up doing (expanding on the @john.k.doe approach):
Using Xcode 7.2, Swift 2
- In the Storyboard, add a
Navigation Item
to the Parent View Controller scene (not the child VC)
- On the
Attributes Inspector
of your new Navigation Item
, type in a space
character in the Back Button
field. More on this later.
- In the Parent view controller, add the following code:
snippet:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.destinationViewController {
case is ChildViewController:
navigationItem.backBarButtonItem?.title = ""
default:
navigationItem.backBarButtonItem?.title = "Full Parent Title"
}
}
Explanation:
The back button sort of belongs to the parent view controller. The Navigation Item
gives you a handle to the back button, so you can set the title in code or in the Storyboard.
Note:
If you leave the Navigation Item
Back Button
text as the default empty string, the back button title will become "Back".
Other approaches work, why use this one?:
While it's possible to override the back button title on the child view controller, it was a challenge getting a handle to it until it had already flashed briefly on the screen.
Some of the approaches construct a new back button and override the existing one. I'm sure it works, and probably necessary in some use cases. But I prefer to leverage existing APIs when possible.
Changing the title
of the parent view controller is the quickest solution for some situations. However, this changes the parent title so you have to manage state. Things also get messy with a Tab Bar Controller
because title changes cause side effects with the Tab Bar Item
titles.