How to present UIAlertController when not in a view controller?

前端 未结 30 3152
庸人自扰
庸人自扰 2020-11-22 06:21

Scenario: The user taps on a button on a view controller. The view controller is the topmost (obviously) in the navigation stack. The tap invokes a utility class method call

30条回答
  •  情话喂你
    2020-11-22 06:56

    Adding on to Zev's answer (and switching back to Objective-C), you could run into a situation where your root view controller is presenting some other VC via a segue or something else. Calling presentedViewController on the root VC will take care of this:

    [[UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController presentViewController:alertController animated:YES completion:^{}];
    

    This straightened out an issue I had where the root VC had segued to another VC, and instead of presenting the alert controller, a warning like those reported above was issued:

    Warning: Attempt to present  on  whose view is not in the window hierarchy!
    

    I haven't tested it, but this may also be necessary if your root VC happens to be a navigation controller.

提交回复
热议问题