警告:尝试呈现其视图不在窗口层次结构中的<UIAlertController>

时间:2019-07-26 21:22:38

标签: uialertview uialertcontroller swift5

我正在尝试为我的应用创建并显示一个UIalert。此警报的问题在于,我试图通过在视图控制器外部的类中编写代码来制作和显示警报。 (在视图控制器外部的类中进行此操作很重要,因为我在UserApi类中还存在其他与我的警报所针对的配置文件图像有关的语句。)关于如何使用它的任何想法为此,我不会收到错误

  

“警告:尝试显示<UIAlertController.....>:其视图不在窗口层次结构中!”

我已经尝试使用UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true)代替present(alertController, animated: true)。我收到同样的错误。

class UserApi : UIAlertController {

    func signUp()....

   //detect if user hasn't added a profile image and send an alert indicating the user must add a profile image
    guard let imageSelected = image else {

        let alertController = UIAlertController(title: "Profile Image Required", 
            message: "Please add a profile image to proceed." , preferredStyle: .alert)

        let OKAction = UIAlertAction(title: "OK", style: .default)
        alertController.addAction(OKAction)
        present(alertController, animated: true)

}
......

2 个答案:

答案 0 :(得分:0)

Guard let 语句中,需要 return 语句,请替换以下代码,然后重试。一切正常。

   guard let imageSelected = image  else {
      let alertController = UIAlertController(title: "Profile Image Required",
                                              message: "Please add a profile image to proceed." , preferredStyle: .alert)

      let OKAction = UIAlertAction(title: "OK", style: .default)
      alertController.addAction(OKAction)
      present(alertController, animated: true)
      return
    }

答案 1 :(得分:0)

具有注册功能的传递控制器

喜欢

func signUp(controller:UIViewController){
  let alertController = UIAlertController(title: "Profile Image Required", 
        message: "Please add a profile image to proceed." , preferredStyle: .alert)

    let OKAction = UIAlertAction(title: "OK", style: .default)
    alertController.addAction(OKAction)
    controller.present(alertController, animated: true)
}