【问题标题】:Error when loading UIAlertController加载 UIAlertController 时出错
【发布时间】:2015-09-27 16:32:02
【问题描述】:

我想在互联网连接不可用时加载警报。检查互联网连接的功能已准备就绪,但我无法加载警报。所以我只是在没有任何条件等的情况下将警报代码放在 viewDidLoad 中并得到了这个错误:

警告:尝试在 x.ViewController: 0x127646f00 上呈现 UIAlertController: 0x12752d400,其视图不在窗口层次结构中!

代码:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Delegates
        verificationCode.delegate = self

        let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
        let action = UIAlertAction(title: "OK", style: .Default) { _ in }
        alert.addAction(action)
        self.presentViewController(alert, animated: true) {}


        if (!Util.isConnectedToNetwork()) {
            self.isConnected = false
        }
    }

你能告诉我如何解决它吗?

【问题讨论】:

    标签: swift2 ios9 uialertcontroller


    【解决方案1】:

    错误告诉您出了什么问题。

    您试图在viewDidLoad 中显示视图控制器,但视图虽然已加载,但不在任何层次结构中。尝试将代码放在viewDidAppear 方法中,该方法在视图出现在屏幕上后调用,并且位于视图层次结构中。

    【讨论】:

      【解决方案2】:

      Swift 4 更新 我认为这可以帮助您解决问题:

      override func viewDidLoad() {
          super.viewDidLoad()
      
          verificationCode.delegate = self
      
          let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .alert)
          let delete = UIAlertAction(title: "OK", style: .default) { (_) in }
          let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
          alert.addAction(cancelAction)
          alert.addAction(delete)
      
          alert.popoverPresentationController?.sourceView = sender as UIView
          UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
      
          if (!Util.isConnectedToNetwork()) {
              self.isConnected = false
          }
      }
      

      【讨论】:

        【解决方案3】:

        将代码从 viewDidLoad 移到 viewDidAppear

        override func viewDidAppear(animated: Bool) {
            // Delegates
            verificationCode.delegate = self
        
            let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
            let action = UIAlertAction(title: "OK", style: .Default) { _ in }
            alert.addAction(action)
            self.presentViewController(alert, animated: true) {}
        
        
            if (!Util.isConnectedToNetwork()) {
                self.isConnected = false
            }
        
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-07-12
          • 2014-06-26
          • 2012-11-04
          • 2013-02-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多