Search code examples
iosswiftuiviewcontrolleruinavigationcontrolleruibarbuttonitem

Add another back button to a Navigation Controller


I have a navigation controller so when I click on a button on my main view, it opens another view with the "Back" navigation item.

What I'm trying to do is to add another item on my second view on the right, so this view should have a "Back" item, already working, and a new "Edit" item which does the same thing as Back button but I can get the prepareForSegue function to run some code in complement.

How can I achieve to do that ?

Here is what I tried :

enter image description here

I'm using two navigation controllers because I couldn't add an "Edit" item if my second view wasn't embed in a navigation controller. So this is working, I have my two "Back" and "Edit" items, but I don't know how to manage to get the same behavior as the "Back" item on my "Edit" item, I tried segues but it doesn't work as expected. Note that the button I talked about on my first view isn't shown in the editor nor its segue, I did it programmatically.


Solution

  • You can simple call popViewController(animated:) when the edit button is tapped.

    class ViewController: UIViewController
    {
        override func viewDidLoad()
        {
            super.viewDidLoad()
            let editItem = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editButtonTapped(_:)))
            self.navigationItem.rightBarButtonItem = editItem
    
        }
    
        @objc func editButtonTapped(_ sender: UIBarButtonItem)
        {
            self.navigationController?.popViewController(animated: true)
        }
    }
    

    Storyboard:

    enter image description here