Swift 3:
If you want to go back to the previous view controller
_ = navigationController?.popViewController(animated: true)
If you want to go back to the root view controller
_ = navigationController?.popToRootViewController(animated: true)
If you are not using a navigation controller then pls use the below code.
self.dismiss(animated: true, completion: nil)
animation value you can set according to your requirement.
Swift 3, Swift 4
if movetoroot {
navigationController?.popToRootViewController(animated: true)
} else {
navigationController?.popViewController(animated: true)
}
navigationController is optional because there might not be one.
Swift 3
I might be late in the answer but for swift 3 you can do it this way:
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "< Back", style: .plain, target: self, action: #selector(backAction))
// Do any additional setup if required.
}
func backAction(){
//print("Back Button Clicked")
dismiss(animated: true, completion: nil)
}
Swift 4
there's two ways to return/back to the previous ViewController :
self.navigationController?.pushViewController(yourViewController, animated: true)
in this case you need to use self.navigationController?.popViewController(animated: true)
self.present(yourViewController, animated: true, completion: nil)
in this case you need to use self.dismiss(animated: true, completion: nil)
In the first case , be sure that you embedded your ViewController to a navigationController in your storyboard
swift 5 and above
case 1 : using with Navigation controller
self.navigationController?.popViewController(animated: true)
case 2 : using with present view controller
self.dismiss(animated: true, completion: nil)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With