首页 > 解决方案 > 在全局 swift 文件中添加警报控制器?

问题描述

我正在尝试在文件以外的 swift 文件中创建一个警报框UIViewController。但我无法创建它。

extension NetworkManager {

    func showAlert(message: String,from:UIViewController, title: String = "") {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(OKAction)
        from.present(alertController, animated: true, completion: nil)
    }
}

上面的代码是用于实现 alertcontroller 但我不知道如何传递我需要呈现的视图控制器,所以需要帮助。

标签: iosswift

解决方案


extension UIViewController {
     func showAlert(message: String, title: String = "") {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(OKAction)
        self.present(alertController, animated: true, completion: nil)
    }    
}

并像这样使用

from.showAlert(message:"Your message", title: "Title")

推荐阅读