如何弹出视图控制器然后显示 UIAlertController

Luc*_*rif 1 swift uialertcontroller swift4

假设 ViewController2 中有错误,我想回到 ViewController1,前一个视图控制器,然后显示警报。现在如果我把它放在 ViewController2 中

    @IBAction func testing(_ sender: Any) {
    navigationController?.popViewController(animated: true)
    Alert.alert(userTitle: "Error", userMessage: " ", userOptions: " ", in: LandingViewController() as UIViewController)

}
Run Code Online (Sandbox Code Playgroud)

使用它作为警报类

    public class Alert {
    class func alert(userTitle: String?, userMessage: String, userOptions: String, in vc: UIViewController) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: userTitle, message: userMessage, preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: userOptions, style: UIAlertActionStyle.default, handler: nil))
            vc.present(alert, animated: true, completion: nil)
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

它会抛出错误

那么有没有办法做到这一点?

Car*_*ndo 6

问题是LandingViewController() as UIViewController未在 UiWindow 中呈现

尝试这个

guard let nav = navigationController, let top = nav.topViewController else {
    return
}

nav.popViewController(animated: true)
Alert.alert(userTitle: "Error", userMessage: " ", userOptions: " ", in: top)
Run Code Online (Sandbox Code Playgroud)