关闭View Controller后显示警报

时间:2020-06-12 13:00:15

标签: ios swift xcode uiviewcontroller uialertcontroller

我正在使用最新的XcodeSwift版本。

我正在像这样显示一个特定的View Controller

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let contactViewController = storyboard.instantiateViewController(identifier: "contactViewController")
show(contactViewController, sender: self)

我正在这样解雇View Controller

self.presentingViewController?.dismiss(animated: true, completion: nil)

我想在撤消UIAlertController之后立即提出View Controller

此:

self.presentingViewController?.dismiss(animated: true, completion: nil)

let alertMessage = UIAlertController(title: "Your message was sent", message: "", preferredStyle: .alert)
let alertButton = UIAlertAction(title: "Okay", style: UIAlertAction.Style.default)
alertMessage.addAction(alertButton)
self.present(alertMessage, animated: true, completion: nil)

…当然不起作用,因为我无法在被解雇的UIAlertController上出示View Controller

UIAlertController被解散后,呈现此View Controller的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

您可以通过获取像这样的顶级控制器来在完成处理程序中完成

self.presentingViewController?.dismiss(animated: true, completion: {
            let alertMessage = UIAlertController(title: "Your message was sent", message: "", preferredStyle: .alert)
               let alertButton = UIAlertAction(title: "Okay", style: UIAlertAction.Style.default)
               alertMessage.addAction(alertButton)
            UIApplication.getTopMostViewController()?.present(alertMessage, animated: true, completion: nil)
        })

使用此扩展名

extension UIApplication {

    class func getTopMostViewController() -> UIViewController? {
        let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
        if var topController = keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController
            }
            return topController
        } else {
            return nil
        }
    }
}

答案 1 :(得分:0)

使用 Jawad Ali 的扩展,我们可以锚定当前呈现的 ViewController。

如果您想稍后解除该警报,您可以在另一个完成处理程序中执行此操作,如下面的代码所示。就我而言,我将一首歌曲保存到一个播放列表中,然后关闭该播放列表并显示一个短时间提醒,让用户知道可以保存。

<20