How to present UIAlertController when not in a view controller?

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

    @agilityvision's answer translated to Swift4/iOS11. I haven't used localized strings, but you can change that easily:

    import UIKit
    
    /** An alert controller that can be called without a view controller.
     Creates a blank view controller and presents itself over that
     **/
    class AlertPlusViewController: UIAlertController {
    
        private var alertWindow: UIWindow?
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        override func viewDidDisappear(_ animated: Bool) {
            super.viewDidDisappear(animated)
            self.alertWindow?.isHidden = true
            alertWindow = nil
        }
    
        func show() {
            self.showAnimated(animated: true)
        }
    
        func showAnimated(animated _: Bool) {
    
            let blankViewController = UIViewController()
            blankViewController.view.backgroundColor = UIColor.clear
    
            let window = UIWindow(frame: UIScreen.main.bounds)
            window.rootViewController = blankViewController
            window.backgroundColor = UIColor.clear
            window.windowLevel = UIWindowLevelAlert + 1
            window.makeKeyAndVisible()
            self.alertWindow = window
    
            blankViewController.present(self, animated: true, completion: nil)
        }
    
        func presentOkayAlertWithTitle(title: String?, message: String?) {
    
            let alertController = AlertPlusViewController(title: title, message: message, preferredStyle: .alert)
            let okayAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
            alertController.addAction(okayAction)
            alertController.show()
        }
    
        func presentOkayAlertWithError(error: NSError?) {
            let title = "Error"
            let message = error?.localizedDescription
            presentOkayAlertWithTitle(title: title, message: message)
        }
    }
    

提交回复
热议问题