In an iOS app, how can I determine whether a back button is displayed? Ideally, I’d like to know this in my controller’s loadView method.
Here’s what I’ve tried in loadView, viewDidLoad, and viewWillAppear:
if (self.navigationItem.backBarButtonItem)
and this:
if (self.navigationItem.leftBarButtonItem)
Neither of those work – they’re always nil (the expression evaluates to false), even when there is a back button on the screen. What I’d ultimately like to do is set a Cancel button as the self.navigationItem.leftBarButtonItem, but only if there’s no back button. If there is a back button, we don’t need the Cancel button. As it is, setting the leftBarButtonItem is overriding the back button, so we’re seeing a Cancel button all the time – even when there should be a back button.
You’re asking the wrong object for its
backBarButtonItem. This property controls how an object is represented when it is the “back” item in the navigation stack.Therefore, you need to be asking the view controller at the level below where you are in the navigation stack what its
backBarButtonItemis:You may need to check if the navigation controller has added your viewController to the stack at the time you are executing this code, the top view controller may still be the previous one. I’ve checked in
viewWillAppearand the stack does contain the new top controller at this point.