在视图顶部呈现警报控制器,Swift

时间:2017-10-27 06:58:58

标签: ios swift swift3 uialertcontroller

我有一个视图,它是keyWindow的子视图(如下面的代码所示)。我想在此视图(myView)上显示alertController。

我试图在topViewController上呈现alertController(如下所示),这不起作用,因为我的视图不是topViewController的一部分。

如何在视图顶部显示alertController?

这就是我向keyWindow添加视图的方式

guard let window = UIApplication.shared.keyWindow else{
    return
}

window.addSubview(myView)

由于视图不是topViewController的一部分,所以下面没有用。

guard let vc = UIApplication.topViewController() else { return}
vc.present(alertController, animated: true, completion: nil)

1 个答案:

答案 0 :(得分:0)

试试这个

func showAlertMessage(title:String? = nil, _ message:String) {
    let rootVC = APP_DELEGATE.window?.topMostController()
    var alert = UIAlertController(title: message, message: nil, preferredStyle: .alert)
    if let title = title {
        alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    }
    alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
    rootVC?.present(alert, animated: true, completion: nil)

}