How to present UIAlertController when not in a view controller?

前端 未结 30 3569
庸人自扰
庸人自扰 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 06:57

    Pretty generic UIAlertController extension for all cases of UINavigationController and/or UITabBarController. Also works if there's a modal VC on screen at the moment.

    Usage:

    //option 1:
    myAlertController.show()
    //option 2:
    myAlertController.present(animated: true) {
        //completion code...
    }
    

    This is the extension:

    //Uses Swift1.2 syntax with the new if-let
    // so it won't compile on a lower version.
    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)
              }
            }
        }
    }
    

提交回复
热议问题