在 ViewController 之外显示 UIAlertController

show UIAlertController outside of ViewController

我无法显示我的 UIAlertController,因为我试图在 Class 中显示它,而不是 ViewController.

我已经尝试添加它了:

 var alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)

UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

哪个不起作用... 我还没有找到适合我的解决方案。

创建一个从当前视图控制器调用的辅助函数,并将当前视图控制器作为参数传递:

func showAlertInVC(
  viewController: UIViewController, 
  title: String, 
message: String)
{
  //Code to create an alert controller and display it in viewController
}

如果您的解决方案不起作用,可能是因为当时没有 window。当我试图在 application:DidFinishLoadingWithOptions 方法中显示警报视图时,我遇到了同样的问题。在这种情况下,我的解决方案是检查根视图控制器是否可用,如果不可用,则为 UIApplicationDidBecomeActiveNotification

添加通知
NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidBecomeActiveNotification,
                object: nil,
                queue: NSOperationQueue.mainQueue()) {
                    (_) in
                        //show your alert by using root view controller
                        //remove self from observing
                    }
        }

我在 UIAlertController 上写了这篇 extension 以带回 show()
它使用递归来查找当前的顶视图控制器:

extension UIAlertController {
    
    func show() {
        present(animated: true, completion: nil)
    }
    
    func present(animated: Bool, completion: (() -> Void)?) {
        if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
            presentFromController(controller: rootVC, animated: animated, completion: completion)
        }
    }
    
    private func presentFromController(controller: UIViewController, animated: Bool, completion: (() -> Void)?) {
        if 
            let navVC = controller as? UINavigationController,
            let visibleVC = navVC.visibleViewController
        {
            presentFromController(controller: visibleVC, animated: animated, completion: completion)
        } else if
            let tabVC = controller as? UITabBarController,
            let selectedVC = tabVC.selectedViewController
        {
            presentFromController(controller: selectedVC, animated: animated, completion: completion)
        } else if let presented = controller.presentedViewController {
            presentFromController(controller: presented, animated: animated, completion: completion)
        } else {
            controller.present(self, animated: animated, completion: completion);    
        }
    }
}

现在就这么简单:

var alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
alertController.show()

这应该有效。

 UIApplication.sharedApplication().windows[0].rootViewController?.presentViewController(...)