13
votes

I'm trying to disable a navigation bar back button item (turning to gray and does not respond to touches).

I tried the following :

[self.navigationItem.backBarButtonItem setEnabled:NO];

Which does not work. Disabling the right button item works as a charm.

Surprisingly enough I could not find a similar question on SO. The closest one was about hiding the button (which works btw) but this is not so elegant (or adding a label to cover the button and prevent touches which keeps the same color of the back button --> also not so elegant:/).

I should mention that the view controller is a table view controller which is pushed by another navigation controller. (i.e. the back button is added automatically and not via IB or programmaticaly)

Any ideas ?

2
Does setting tableViewController.navigationItem.leftBarButton to nil work?erdekhayser
that doesn't work. Button is still enabled...giorashc
but this hides the button completely. I want the button to be disabled (grayed out) the same as happens with the right button itemgiorashc
i think that with the default back button you can't. you could create a custom button and at that point you can disable it. or you can get a custom action to default back button and detect the user pressIlario
"Surprisingly enough I could not find a similar question on SO"... and surprisingly enough this question was not so upvoted. +1Martin

2 Answers

9
votes

You can hide using

[self.navigationItem setHidesBackButton:YES animated:YES];
1
votes

You do need to create a custom back button in order to disable it. Here's a simple example (No need to hide the backButtonItem):

Note that you'll probably want to disable the back swipe gesture (see here: How to disable back swipe gesture in UINavigationController on iOS 7 )

class MyClass: UIViewController {
    private var backButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()

        backButton = UIBarButtonItem(title: "Back", style: .Plain, target: self, action: "goBack")

        navigationItem.leftBarButtonItem = backButton
    }

    func goBack() {
        navigationController?.popViewControllerAnimated(true)
    }

    func toggleBackButton() {
        backButton.enabled = (backButton.enabled == false) ? true : false
    }
}