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)
}
}