2

iOS14 introduced that long-press on back button which opens a callout menu to go back to specific VC in stack.

I would like to disable it, is there a possibility to do such a thing, and if yes how ?

Thanks

Cublax
  • 873
  • 1
  • 9
  • 17

2 Answers2

10

Try to set backButtonDisplayMode to .minimal on your VC ->

if #available(iOS 14.0, *) {
    navigationItem.backButtonDisplayMode = .minimal
}

https://developer.apple.com/documentation/uikit/uinavigationitem/3656350-backbuttondisplaymode

charlyatwork
  • 1,126
  • 8
  • 13
  • 1
    I upvoted but it actually doesn't work – Cublax Oct 16 '20 at 14:15
  • 5
    To elaborate on @charleyatwork's answer, if you have ended up with a blank menu because you were setting `title` or `backButtonTitle` to an empty string to have just the chevron icon, you can use this snippet but in an `else` block continue to set `backButtonTitle = ""` to get the best of both worlds. – chedabob Feb 09 '21 at 08:14
  • 1
    Yes, this works beautifully in iOS14, to replace the previous "hack" of setting the `backButtonTitle`. – Claus Jørgensen Mar 11 '21 at 10:23
8

It can be done by subclassing UIBarButtonItem. Setting the menu to nil on a UIBarButtonItem doesn't work, but you can override the menu property and prevent setting it in the first place.

class BackBarButtonItem: UIBarButtonItem {
  @available(iOS 14.0, *)
  override var menu: UIMenu? {
    set {
      /* Don't set the menu here */
      /* super.menu = menu */
    }
    get {
      return super.menu
    }
  }
}

Then you can configure the back button in your view controller the way you like, but using BackBarButtonItem instead of UIBarButtonItem:

let backButton = BackBarButtonItem(title: "BACK", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton

This is the preferred way because you set the backBarButtonItem only once in your view controller's navigation item, and then whatever view controller it will be pushing, the pushed controller will show the back button automatically on the nav bar. If using leftBarButtonItem instead of backBarButtonItem, you will have to set it on every view controller that will be pushed.

ANTRIKSH VERMA
  • 293
  • 2
  • 5