Go Back To Previous View Controller In Swift

By Eddy Chung

Sometimes you’ll want to go back to the previous view controller without the user hitting the back button.

Maybe the user has entered invalid data or there is some kind of error.

Here is the code example:

func goBack()  {
    if let nav = self.navigationController {
        nav.popViewController(animated: true)
    } else {
        self.dismiss(animated: true, completion: nil)
    }
}

Here’s an example of going back when a user clicks on a specific label:

@IBOutlet weak var label: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    let tap = UITapGestureRecognizer(target: self, action: #selector(goBack))
    label.addGestureRecognizer(tap)
}

@objc func goBack() {
    if let nav = self.navigationController {
        nav.popViewController(animated: true)
    } else {
        self.dismiss(animated: true, completion: nil)
    }
}
If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts