我有一个UIViewController,它从服务器加载一些json数据。如果服务器关闭或用户已关闭数据,我会发出警告告诉用户。这是使用UIAlertController完成的。这非常有效。所以我把它放到一个扩展中,因为它被所有需要数据的UIViewControllers使用。现在UIAlertController也有一个动作集
警报代码
extension UIViewController {
func connectionLost(){
var message = "Your device has lost connection to the server. Check that you have a valid internet connection and then retry."
let alertController = UIAlertController( title: "Connection Lost",
message: message,
preferredStyle: .alert)
let retryAction = UIAlertAction(title:"Retry", style: .default, handler: {
action in
//call function in the viewcontroller that raised this alert to reload the data
})
alertController.addAction(retryAction)
self.present(alertController, animated: true, completion: nil)
}
}
当用户点击重试按钮时,我想调用提升警报的uiviewcontroller中的一个函数。
我尝试在扩展程序中创建一个委托但是很难像在课堂上那样连接它。有什么方法可以从viewcontroller中的扩展调用一个函数来引发警报?
答案 0 :(得分:2)
您应该创建一个BaseViewController并使用Inheritance。它也可能对其他实现有用。
sum
答案 1 :(得分:0)
希望这是有道理的。
class MyVC: UIViewController {
func retry() {
}
func checkConnection() {
connectionLost { (retry) -> (Void) in
if retry {
self.retry()
}
}
}
}
extension UIViewController {
func connectionLost(completion: @escaping (_ retry: Bool) -> (Void)) {
let message = "Your device has lost connection to the server. Check that you have a valid internet connection and then retry."
let alertController = UIAlertController( title: "Connection Lost",
message: message,
preferredStyle: .alert)
let retryAction = UIAlertAction(title:"Retry", style: .default, handler: {
action in
completion(true)//may be 'false', you decide
})
alertController.addAction(retryAction)
self.present(alertController, animated: true, completion: nil)
}
}