markhorrocks
markhorrocks

Reputation: 1388

Swift 3 how to dismiss UIViewController after UIAlertController action

I have an alert controller and want to close the view controller after pressing OK but can't figure out how. self.dismiss(animated: true) only closes the alert controller itself. Here is my code.

let alertController: UIAlertController = UIAlertController(title: "Password updatd", message: "Your password has been changed successfully", preferredStyle: .alert)

let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

alertController.addAction(okAction)

self.present(alertController, animated: true, completion: nil)

I tried this which only removed the current view controller but not back to the root view controller.

let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in
self.navigationController?.popToRootViewController(animated: true)}

This gave me a warning expression of type UIViewController is unused.

Upvotes: 0

Views: 2574

Answers (1)

Denis
Denis

Reputation: 578

Navigation Controller:

Previous Controller

self.navigationController?.popViewController(animated: true)

Root Controller

self.navigationController?.popToRootViewController(animated: true)

Modal View Controller:

self.dismiss(animated: true, completion: nil)

Upvotes: 3

Related Questions