简体   繁体   中英

Do alert views need to be presented from the top view controller?

When presenting an UIAlertController is it necessary to use the top most UIViewcontroller on the screen? Does this UIViewController need to be visible or just in the view hierarchy? Would there be any disadvantage if presenting any alert directly from the UIWindow 's root viewController?

In my opinion there is nothing wrong in presenting from the root view controller of the application. Take a look at the following question and the accepted answer How to present UIAlertController when not in a view controller?

I've used a category on UIAlertViewController similar to what have been proposed in the answers in the above link, and I've never faced any problem.

I think it's better to present the UIAlertViewController from the currently presented view controller. For me I used to get the currently presented view controller like this:

UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
UIViewController *viewController = keyWindow.rootViewController;
while (viewController.presentedViewController) {
    viewController = viewController.presentedViewController;
}
[viewController presentViewController:alertController animated:YES completion:nil]

Using the root to present the view controller caused an issue for me before but I can't remember actually. You're at the safe side while using the top most one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM