How to present UIAlertController when not in a view controller?

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

    iOS13 scene support (when using UIWindowScene)

    import UIKit
    
    private var windows: [String:UIWindow] = [:]
    
    extension UIWindowScene {
        static var focused: UIWindowScene? {
            return UIApplication.shared.connectedScenes
                .first { $0.activationState == .foregroundActive && $0 is UIWindowScene } as? UIWindowScene
        }
    }
    
    class StyledAlertController: UIAlertController {
    
        var wid: String?
    
        func present(animated: Bool, completion: (() -> Void)?) {
    
            //let window = UIWindow(frame: UIScreen.main.bounds)
            guard let window = UIWindowScene.focused.map(UIWindow.init(windowScene:)) else {
                return
            }
            window.rootViewController = UIViewController()
            window.windowLevel = .alert + 1
            window.makeKeyAndVisible()
            window.rootViewController!.present(self, animated: animated, completion: completion)
    
            wid = UUID().uuidString
            windows[wid!] = window
        }
    
        open override func viewDidDisappear(_ animated: Bool) {
            super.viewDidDisappear(animated)
            if let wid = wid {
                windows[wid] = nil
            }
    
        }
    
    }
    

提交回复
热议问题