Reputation: 4632
self.navigationItem.backBarButtonItem!.title
causes fatal error: unexpectedly found nil while unwrapping an Optional value while clearly there is a back button with title string in it in my view controller
How do I get the back button's title string?
Upvotes: 0
Views: 476
Reputation: 15331
When you reference self.navigationItem.backBarButtonItem
you should be aware that this is the bar button item that will be used in the navigation bar when self
is not the topViewController
but rather immediately below the topViewController
. That is self.navigationItem.backBarButtonItem
is not the button currently visible when self
is the topViewController
but when another view controller is pushed on top of it.
You should also be aware:
When this property is nil, the navigation item uses the value in its title property to create an appropriate back button.
Meaning that self.navigationItem.backBarButtonItem
can be nil
and still have a title. See here
If you want to know what text is being used with the back button You could could say something like:
extension UINavigationController {
var backButtonText: String? {
guard let self.viewControllers.count > 1 else { return nil }
let viewController = self.viewControllers[self.viewControllers.count - 2]
return viewController.navigationItem.backBarButtonItem?.title ?? viewController.title
}
}
Which could be called like:
print(self.navigationController?.backButtonText ?? "No back button title")
Upvotes: 1