我使用的是最新的Xcode
和Swift
版本。
我将展示一个特定的视图控制器
,如下所示:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let contactViewController = storyboard.instantiateViewController(identifier: "contactViewController")
show(contactViewController, sender: self)
我正在按如下方式删除此视图控制器
:
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)
…当然不起作用了,因为我不能在被取消的视图控制器
上显示UIAlertController
。
解除视图控制器
后,显示此UIAlertController
的最佳方式是什么?
您可以在完成处理程序中通过获取top 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
}
}
}