Go Back To Previous View Controller In Swift

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 and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts