iphone - 从扩展调用 UIViewController 中的函数

标签 iphone swift uiviewcontroller

我有一个 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/

相关文章:

iphone - 用户单击“主页”按钮时如何显示退出确认对话框?

ios - NSUserDefaults 不使用共享扩展保存到磁盘

ios - 为什么我的静态库会出现 iOS 链接器错误?

ios - Swift 中的完成处理程序错误

swift - 试图将数据从 UICollectionViewCell 传递到 UIViewController

ios - DismissViewControllerAnimated 关闭超过 1 个 Controller

ios - 没有上下文的 CoreData 关系设置?

iphone - 如何在 iPhone 的导航栏中添加自定义颜色?

ios - 是否可以在应用程序中关闭设备(iPhone/iPad)?

iphone - 为什么 ViewController 类的单独实例会影响前一个实例?