在 window 上显示 UIAlertView

Present UIAlertView on window

有可能,我的控制器上有自定义视图,我必须在其上显示警报。所以我使用下面的扩展在 window 而不是任何 UIViewController 上呈现控制器。

分机

extension UIViewController {
    func presentControllerToWindow(){
        let win = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        win.rootViewController = vc
        win.windowLevel = UIWindow.Level.alert + 1
        win.makeKeyAndVisible()
        vc.present(self, animated: true, completion: nil)
    }
}

当前 AlertController

let alertController = UIAlertController(title: nil, message: "Select Option", preferredStyle: .alert)

alertController.presentControllerToWindow()

Issue :

代码在 swift 4.X 之前工作正常,但在 swift 5.X 中,警报控制器出现并在另一秒自动关闭。

GIF:

  1. OpenPicker 添加自定义视图作为子视图。
  2. 单击添加文件后,我将显示 alertcontroller。
  3. 自动关闭。

Edit :

我正在添加我的自定义视图,如下所示。

extension UIView {

    func addToWindow()  {
        let window = UIApplication.shared.keyWindow!
        self.frame = window.bounds
        window.makeKeyAndVisible()
        window.windowLevel = window.windowLevel + 1
        window.addSubview(self)
    }
}

let customView = MyCustomView()
customView.addToWindow()

现在这个 MyCustomView,我需要显示 UIAlertController

我个人使用以下扩展来创建警报。

extension UIViewController {
  func showAlert(withTitle title: String?, message: String?) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
  }
}

与 iOS 13

配合使用效果很好

您必须在 UIApplication keyWindow

中添加您的 UIViewController 视图
extension UIViewController {
    func presentControllerToWindow(){
        let win = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        win.rootViewController = vc
        win.windowLevel = UIWindow.Level.alert + 1
        win.makeKeyAndVisible()
        UIApplication.shared.keyWindow?.addSubview(vc.view) //added
        vc.present(self, animated: true, completion: nil)
    }
}