Search code examples
swiftxcodenavigationstoryboarduinavigationbar

How to make backBarButton work in modal presentation?


I need to present second VC modally. At first the nav bar did not appear on second vc, so I did the following: add new Nav controller, set presentation to be full screen. Like shown here:
https://i.sstatic.net/Y9hJn.jpg
Then I choose navigation item in second VC and type a name for a back button enter image description here

Then the button appears in Navigation Item and I drag it to View Controller enter image description here

All in all it looks like this: enter image description here

The problem is: the back button does not take me back when I run the app, it does nothing. What am I missing?


Solution

  • Segues are generally used to go forward (unless you use unwind segues). Since you want to go back, you should create an IBAction in the ViewController with the back button. Then link the back button to this IBAction and dismiss the ViewController in the method body

    @IBAction func btnBackPressed(_ sender: UIBarButtonItem) {
        dismiss(animated: true, completion: nil)
    }