How to present UIAlertController when not in a view controller?

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

    If anyone is interested I created a Swift 3 version of @agilityvision answer. The code:

    import Foundation
    import UIKit
    
    extension UIAlertController {
    
        var window: UIWindow? {
            get {
                return objc_getAssociatedObject(self, "window") as? UIWindow
            }
            set {
                objc_setAssociatedObject(self, "window", newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    
        open override func viewDidDisappear(_ animated: Bool) {
            super.viewDidDisappear(animated)
            self.window?.isHidden = true
            self.window = nil
        }
    
        func show(animated: Bool = true) {
            let window = UIWindow(frame: UIScreen.main.bounds)
            window.rootViewController = UIViewController(nibName: nil, bundle: nil)
    
            let delegate = UIApplication.shared.delegate
            if delegate?.window != nil {
                window.tintColor = delegate!.window!!.tintColor
            }
    
            window.windowLevel = UIApplication.shared.windows.last!.windowLevel + 1
    
            window.makeKeyAndVisible()
            window.rootViewController!.present(self, animated: animated, completion: nil)
    
            self.window = window
        }
    }
    

提交回复
热议问题