努力与以下代码:
var connected = false
while !connected {
let msg = "Press cancel"
let alert = UIAlertController(title: "Test", message: msg, preferredStyle: .alert)
let action = UIAlertAction(title: "Cancel", style: .default) { (action:UIAlertAction) in
connected = true
}
alert.addAction(action)
print ("Hello")
present(alert, animated: true, completion: nil)
}
我究竟做错了什么?
最佳答案
首先,如评论中所述,在while循环中连续显示警报控制器不是一个好主意。我相信您的预期功能是在connected
变量变为false时显示警报。
为此,请使用NotificationCenter
进行如下响应:
在viewDidLoad
中:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.displayAlert), name: NSNotification.Name(rawValue: "connectionDropped"), object: nil)
将
willSet
属性观察者添加到connected
中:var connected: Bool! {
willSet {
if newValue == false && oldValue != false {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "connectionDropped"), object: nil)
}
}
}
然后,无论何时设置
self.connected = false
,都将运行此方法:@objc func displayAlert() {
let msg = "Press cancel"
let alert = UIAlertController(title: "Test", message: msg, preferredStyle: .alert)
let action = UIAlertAction(title: "Cancel", style: .default) { (action:UIAlertAction) in
self.connected = true
}
alert.addAction(action)
print ("Hello")
present(alert, animated: true, completion: nil)
}
只需确保在视图层次结构已加载后(例如
viewDidAppear
)中将其设置为connected即可。一旦完成了视图,就可以删除观察者:
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "connectionDropped"), object: nil)
}
编辑:
所需的功能随Reachability框架一起提供,尤其是随
reachabilityChanged
通知一起提供。然后,您可以使用上面概述的类似方法来调用displayAlert
;这记录在他们的自述文件中。关于ios - swift :while循环内的UIAlertController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46141093/