13

I would like to present a simple UIAlertController to the user with one of the options triggering the closing of the parent view controller. Here is the code that I am using:

    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

    alert.addAction(UIAlertAction(title: "Close View", style: UIAlertActionStyle.Destructive, handler: {
        action in

        self.dismissViewControllerAnimated(true, completion: nil)
    }))

    alert.addAction(UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.Cancel, handler: nil))

    self.presentViewController(alert, animated: true, completion: nil)

It doesn't have any effect. After executing the "Close View" handler the view controller that presents the alert is still there.

I also tried self.navigationController?.dismissViewControllerAnimated(true, completion: nil) in the UIAlertAction action block but that didn't work either.

Chris Balavessov
  • 805
  • 8
  • 14

2 Answers2

17

Using

self.navigationController?.popViewControllerAnimated(true)

instead of

self.dismissViewControllerAnimated(true, completion: nil)

works as required and closes the view controller which displays the alert.

Chris Balavessov
  • 805
  • 8
  • 14
0

You use presentViewController to present alert. So if you use self.dismissViewController, it just dismisses the alert , not the parent view controller. If you try to hidden the parent view controller, you can create a view that width height equal to self.view and give it black color. Then use view.addSubView to add it in anytime you want.

Arco
  • 614
  • 5
  • 13