简体   繁体   中英

Swift how to preserve navigation bar button items after push

In my root view controller I set an array of bar button items with images and assign them to the right bar button.

When I push the next view controller my navigation bar resets and only displays a back button.

Any way to preserve the navigation bar as it was set on the root view controller so it will display on all pages?

As user1046037 has said you can set the item buttons while you are preparing the segue.

Example:

let helpViewController = HelpViewController(nibName: "HelpViewController", bundle: nil)
let someLeftButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.refresh, target: self, action: "someAction")
helpViewController.navigationItem.leftBarButtonItem = someLeftButton
helpViewController.navigationItem.leftItemsSupplementBackButton = true
navigationController?.pushViewController(helpViewController, animated: true)

This one is to preserve the left button item and the back one.

helpViewController.navigationItem.leftItemsSupplementBackButton = true

If you are going to use the same button in several Viewcontrollers you can create a BaseViewController setting up the button and his behaviors.

class AHBaseViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    configureNavigationBar()
    // Configure Common status bar if you want too.
  }

  func configureNavigationBar() {
    let someLeftButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.refresh, target: self, action: "someAction")
    navigationItem.leftBarButtonItem = someLeftButton
    navigationItem.leftItemsSupplementBackButton = true
  }
}

Then just inherit it, in the viewControllers that you want to show the button(s).

class HelpViewController: AHBaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

When you segue between view controllers using Push, you're going to get the default "horizontal slide" navigation animation which. Try "present Modally" or "present as popover".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM