我有一个 UIViewController,它从服务器加载一些 json 数据。如果服务器关闭或用户关闭了数据,我会发出警告告诉用户。这是使用 UIAlertController 完成的。这很好用。所以我把它放到一个扩展中,因为它被所有需要数据的 UIViewControllers 使用。现在 UIAlertController 也有一个 Action 集
警报代码
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 中引发警报的函数。
我尝试在扩展中创建一个委托(delegate),但很难像在类里面那样连接它。有哪些方法可以从引发警报的 View Controller 中的扩展调用函数?
最佳答案
您应该创建一个 BaseViewController 并使用 Inheritance .它也可能对其他实现有用。
class BaseViewController: UIViewController {
func onRetryClick() {
// override to customize or write here the common behaviour
}
}
class FirstViewController: BaseViewController {
override func onRetryClick() {
// do something specific for FirstViewController
}
}
class SecondViewController: BaseViewController {
override func onRetryClick() {
// do something specific for SecondViewController
}
}
class ThirdViewController: BaseViewController {
// if you don't override this method, super class (BaseViewController) implementation will be executed
}
extension BaseViewController {
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
self.onRetryClick()
})
alertController.addAction(retryAction)
self.present(alertController, animated: true, completion: nil)
}
}
关于iphone - 从扩展调用 UIViewController 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41124205/