show UIAlertController outside of ViewController

前端 未结 4 2129
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 07:43

I have trouble to display my UIAlertController because I\'m trying to show it in a Class which is not an ViewController.

I already tried adding it:

 var          


        
4条回答
  •  伪装坚强ぢ
    2021-02-01 08:33

    I wrote this extension over UIAlertController to bring back show().
    It uses recursion to find the current top view controller:

    extension UIAlertController {
    
        func show() {
            present(animated: true, completion: nil)
        }
    
        func present(#animated: Bool, completion: (() -> Void)?) {
            if let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController {
                presentFromController(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(visibleVC, animated: animated, completion: completion)
            } else
            if let tabVC = controller as? UITabBarController,
                let selectedVC = tabVC.selectedViewController {
                    presentFromController(selectedVC, animated: animated, completion: completion)
            } else {
                controller.presentViewController(self, animated: animated, completion: completion);
            }
        }
    }
    

    Now it's as easy as:

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

    EDIT:

    For Xcode 8.0 & Swift 3:

    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 {
                    controller.present(self, animated: animated, completion: completion);
            }
        }
    }
    

提交回复
热议问题