UIAlertController 去新 ViewController

UIAlertController to go to new ViewController

我已经生成了一个 UIAlert,我想 link 打开一个新的 viewController。我已经为每个不同的 viewcontroller 添加了新文件,并且 link 编辑了 class.

我的密码是..

@IBAction func CorrectButton(_ sender: UIButton) {

    let refreshAlert = UIAlertController(title: "Correct Answer", message: "Congratulations", preferredStyle: UIAlertControllerStyle.alert)

    let vc = ThirdViewController()

    refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in self.present(vc, animated: true, completion: nil)

    }))

    present(refreshAlert, animated: true, completion: nil)
}

基本上,当用户点击正确答案时,警报会弹出,然后当用户点击 "OK" 时,我希望新的 viewcontroller 与应用程序的下一部分一起弹出。当前发生的一切是当我单击警告消息中的 "ok" 时屏幕变黑了?

任何帮助将不胜感激..

在 okButton 的完成处理程序中实例化 viewController 你想去的地方。

这是我使用的示例。它是一个我可以从任何地方调用的 class 函数,我已经硬编码了我想访问的视图控制器,它是导航控制器的一部分,只需将 "LogInNavCont" 更改为你的 viewcontroller 的故事板 ID 和UINavigationController 到 UIViewController 如果它是独立的 viewController.

如果您不想将其用作 class 函数,只需将 className.present 替换为 self.present

class func createAlertAndGoToLogin(errorTitle: String, errorMessage: String, className: UIViewController) {
    let alert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in

        // go back to the login view controller
        // go back through the navigation controller

            let vc = className.storyboard!.instantiateViewController(withIdentifier: "LogInNavCont") as! UINavigationController
            className.present(vc, animated: false, completion: nil)


    }))
    className.present(alert, animated: true, completion: nil)
}