[英]Unable to pushViewController after dismissing present view controller
[英]Present alert after dismissing View Controller
我正在使用最新的Xcode
和Swift
版本。
我正在展示一個特定的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.