【问题标题】:Warning: Attempt to present <UIAlertController> whose view is not in the window hierarchy警告:尝试显示其视图不在窗口层次结构中的 <UIAlertController>
【发布时间】:2019-07-26 21:22:38
【问题描述】:

我正在尝试为我的应用创建并显示 UIalert。这个警报的问题是我试图通过在视图控制器之外的类中编写代码来制作和显示警报。 (在视图控制器之外的类中执行此操作很重要,因为我在 UserApi 类中的其他语句与我的警报所针对的个人资料图像有关。)这样做,这样我就不会收到错误了

“警告:尝试呈现&lt;UIAlertController.....&gt;:谁的视图不在窗口层次结构中!”?

我已经尝试过使用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)

}
......

【问题讨论】:

    标签: uialertview uialertcontroller swift5


    【解决方案1】:

    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
        }
    

    【讨论】:

      【解决方案2】:

      通过注册功能传递控制器

      喜欢

      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)
      }
      

      【讨论】:

        猜你喜欢
        • 2020-08-07
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        • 2018-06-27
        • 1970-01-01
        • 1970-01-01
        • 2019-12-25
        相关资源
        最近更新 更多