AlertController is not in the window hierarchy

前端 未结 8 1762
北荒
北荒 2020-11-29 03:01

I\'ve just created a Single View Application project with ViewController class. I would like to show a UIAlertController from a function which is located inside my own class

8条回答
  •  心在旅途
    2020-11-29 03:27

    This worked for me:

    - (UIViewController *)topViewController{
      return [self topViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    }
    
    - (UIViewController *)topViewController:(UIViewController *)rootViewController
    {
      if (rootViewController.presentedViewController == nil) {
        return rootViewController;
      }
    
      if ([rootViewController.presentedViewController isMemberOfClass:[UINavigationController class]]) {
        UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController;
        UIViewController *lastViewController = [[navigationController viewControllers] lastObject];
        return [self topViewController:lastViewController];
      }
    
      UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController;
      return [self topViewController:presentedViewController];
    }
    

    Implementation:

    UIViewController * topViewController = [self topViewController];
    

    Using with alert:

    [topViewController presentViewController:yourAlert animated:YES completion:nil];
    

    You can send an alert from any class in your app (that uses UIKit: #import )

    Source here.

提交回复
热议问题