簡體   English   中英

關閉視圖后顯示警報 Controller

[英]Present alert after dismissing View Controller

我正在使用最新的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)

我想在關閉View Controller UIAlertController

這個:

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)

…當然不起作用,因為我無法在已關閉的View Controller UIAlertController

View Controller被解除后,呈現此UIAlertController的最佳方式是什么?

您可以像這樣在完成處理程序中獲取頂級 controller

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
        }
    }
}

使用 Jawad Ali 的擴展,我們可以錨定當前呈現的 ViewController。

如果您想稍后解除該警報,您可以在另一個完成處理程序中執行此操作,如下面的代碼所示。 就我而言,我將一首歌曲保存到一個播放列表並關閉此播放列表並顯示一個短時間警報,讓用戶知道保存可以。

DispatchQueue.main.async {
    self?.removeSpinner()
    self?.dismiss(animated: true, completion: {
        let alert = UIAlertController(title: "Save to playlist", message: nil, preferredStyle: .alert)
        UIApplication.getTopMostViewController()?.present(alert, animated: true, completion: {
            Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { _ in
                alert.dismiss(animated: true)
            }
        })
    })
}               

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM