Sunnyside Productions Sunnyside Productions - 16 days ago 5
iOS Question

dismiss UIAlertController presented by a modal view controller

I seem to be running into a problem similar to one in an unresolved posted question: UIAlertController dismissing his presentingViewController

I am presenting a modal view controller on top of a normal UIViewController. Then I'm popping up an alert on that modal view controller. When I push "ok" to dismiss the alert (generated with the code below), the modal view controller is also dismissed.

UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action{
[self dismissViewControllerAnimated: YES completion: nil];}];

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Sign up problem."
message:@"Some fields are empty. Please check your inputs and try again."
preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];


How can I dismiss just the alert?

I realize I can avoid this problem by using a navigation controller type setup instead and hiding the navigation bar, so I Get the same feel as the modal view controller, but this seems silly. Thanks.

Answer

Don't call self dismissViewController in the button handler. That specifically states that you want the view controller dismissed.

You don't need to dismiss the alert. It will automatically dismiss itself. The only thing you should do in the button handler is perform whatever action you need. Do nothing if you don't need to do anything.

If your alert is simply a message and you don't need to perform any action, just do this:

UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];