How to present UIAlertController when not in a view controller?

前端 未结 30 3498
庸人自扰
庸人自扰 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:55

    I tried everything mentioned, but with no success. The method which I used for Swift 3.0 :

    extension UIAlertController {
        func show() {
            present(animated: true, completion: nil)
        }
    
        func present(animated: Bool, completion: (() -> Void)?) {
            if var topController = UIApplication.shared.keyWindow?.rootViewController {
                while let presentedViewController = topController.presentedViewController {
                    topController = presentedViewController
                }
                topController.present(self, animated: animated, completion: completion)
            }
        }
    }
    

提交回复
热议问题