swift2 加载UIAlertController时出错

twh00eeo  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(159)

我想在互联网连接不可用时加载一个警报。检查互联网连接的功能已经准备好了,但我无法加载警报。所以我只是将警报代码放在viewDidLoad中,没有任何条件等,并得到此错误:
警告:尝试显示UIAlertController:x上的0x 12752 d400。视图控制器:0x 127646 f00,其视图不在窗口层次结构中!
编码:

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

你能告诉我怎么修吗?

brgchamk

brgchamk1#

错误会告诉您出了什么问题。
您正尝试在viewDidLoad中显示视图控制器,但该视图虽然已加载,但不在任何层次结构中。请尝试将代码放入viewDidAppear方法中,该方法在视图出现在屏幕上后调用,并且在视图层次结构中。

jbose2ul

jbose2ul2#

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

kb5ga3dv3#

将代码从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
    }

}

相关问题