I send the user over to a page on a button click. This page is a UITableViewController.
Now if the user taps on a cell, I would like to push him ba
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 Segue is Kind of 'Show' or 'Push' then You can invoke "popViewController(animated: Bool)" on Instance of UINavigationController. Or if segue is kind of "present" then call "dismiss(animated: Bool, completion: (() -> Void)?)" with instance of UIViewController
I would like to suggest another approach to this problem. Instead of using the navigation controller to pop a view controller, use unwind segues. This solution has a few, but really important, advantages:
You can find more details in Unwind Segues Step-by-Step. The how to is better explained in the former link, including how to send data back, but here I will make a brief explanation.
1) Go to the destination (not the origin) view controller and add an unwind segue:
@IBAction func unwindToContact(_ unwindSegue: UIStoryboardSegue) {
//let sourceViewController = unwindSegue.source
// Use data from the view controller which initiated the unwind segue
}
2) CTRL drag from the view controller itself to the exit icon in the origin view controller:
3) Select the unwind function you just created a few moments ago:
4) Select the unwind segue and give it a name:
5) Go to any place of the origin view controller and call the unwind segue:
performSegue(withIdentifier: "unwindToContact", sender: self)
I have found this approach payoffs a lot when your navigation starts to get complicated.
I hope this helps someone.
In the case where you presented a UIViewController
from within a UIViewController
i.e...
// Main View Controller
self.present(otherViewController, animated: true)
Simply call the dismiss
function:
// Other View Controller
self.dismiss(animated: true)
I can redirect to root page by writing code in "viewDidDisappear" of navigated controller,
override func viewDidDisappear(_ animated: Bool) {
self.navigationController?.popToRootViewController(animated: true)
}
I did it like this
func showAlert() {
let alert = UIAlertController(title: "Thanks!", message: "We'll get back to you as soon as posible.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
self.dismissView()
}))
self.present(alert, animated: true)
}
func dismissView() {
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}