How to present UIAlertController when not in a view controller?

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

    Updated to work with iOS 13 Scenes which breaks the new UIWindow approach. Swift 5.1.

    fileprivate var alertWindows = [UIAlertController:UIWindow]()
    
    extension UIAlertController {
    
        func presentInNewWindow(animated: Bool, completion: (() -> Void)?) {
            let foregroundActiveScene = UIApplication.shared.connectedScenes.filter { $0.activationState == .foregroundActive }.first
            guard let foregroundWindowScene = foregroundActiveScene as? UIWindowScene else { return }
    
            let window = UIWindow(windowScene: foregroundWindowScene)
            alertWindows[self] = window
    
            window.rootViewController = UIViewController()
            window.windowLevel = .alert + 1
            window.makeKeyAndVisible()
            window.rootViewController!.present( self, animated: animated, completion: completion)
        }
    
        open override func viewDidDisappear(_ animated: Bool) {
            super.viewDidDisappear(animated)
            alertWindows[self] = nil
        }
    
    }
    

提交回复
热议问题