AlertController is not in the window hierarchy

2019-01-07 10:28发布

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.

Here is my class with an alert.

class AlertController: UIViewController {
     func showAlert() { 
         var alert = UIAlertController(title: "abc", message: "def", preferredStyle: .Alert)
         self.presentViewController(alert, animated: true, completion: nil)
     }
}

Here is ViewController which executes the alert.

class ViewController: UIViewController {
   override func viewDidLoad() {
       super.viewDidLoad()  
   }

   @IBAction func showAlertButton(sender: AnyObject) {
       var alert = AlertController()
       alert.showAlert()
   }
}

This is what I get instead of beautiful alert.

Warning: Attempt to present UIAlertController: 0x797d2d20 on Sprint1.AlertController: 0x797cc500 whose view is not in the window hierarchy!

What should I do?

8条回答
Deceive 欺骗
2楼-- · 2019-01-07 11:09

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 <UIKit/UIKit.h> )

Source here.

查看更多
我只想做你的唯一
3楼-- · 2019-01-07 11:10

If you want to create a separate class for displaying alert like this, subclass NSObject not UIViewController.

And pass the ViewControllers reference from which it is initiated, to the showAlert function so that you can present alert view there.

查看更多
登录 后发表回答