How to present UIAlertController when not in a view controller?

前端 未结 30 3154
庸人自扰
庸人自扰 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 07:13

    Here's mythicalcoder's answer as an extension, tested & working in Swift 4:

    extension UIAlertController {
    
        func presentInOwnWindow(animated: Bool, completion: (() -> Void)?) {
            let alertWindow = UIWindow(frame: UIScreen.main.bounds)
            alertWindow.rootViewController = UIViewController()
            alertWindow.windowLevel = UIWindowLevelAlert + 1;
            alertWindow.makeKeyAndVisible()
            alertWindow.rootViewController?.present(self, animated: animated, completion: completion)
        }
    
    }
    

    Example usage:

    let alertController = UIAlertController(title: "", message: "", preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil))
    alertController.presentInOwnWindow(animated: true, completion: {
        print("completed")
    })
    

提交回复
热议问题