13

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 ?

giorashc
  • 13,691
  • 3
  • 35
  • 71
  • Does setting tableViewController.navigationItem.leftBarButton to nil work? – erdekhayser Dec 29 '13 at 20:27
  • that doesn't work. Button is still enabled... – giorashc Dec 29 '13 at 20:40
  • Looked at documentation- set tableViewController.navigationItem.hidesBackButtom = YES – erdekhayser Dec 30 '13 at 03:39
  • 1
    but this hides the button completely. I want the button to be disabled (grayed out) the same as happens with the right button item – giorashc Dec 30 '13 at 08:03
  • 2
    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 press – Ilario Dec 30 '13 at 11:26
  • 1
    "Surprisingly enough I could not find a similar question on SO"... and surprisingly enough this question was not so upvoted. +1 – Martin Jan 14 '14 at 15:43

2 Answers2

9

You can hide using

[self.navigationItem setHidesBackButton:YES animated:YES];
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Gautam Sareriya
  • 1,833
  • 19
  • 30
1

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
    }
}
Community
  • 1
  • 1
Dylan
  • 545
  • 4
  • 15