ios - UIAlertController 在 Swift 3.0 中使用辅助类

标签 ios swift uialertcontroller

我正在为几个函数使用一个帮助程序类,包括一个 UIAlertController,它可以从我的应用程序中的其他地方访问,但是我在从帮助程序类本身访问它时遇到了问题。

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

在课外我可以毫无问题地调用它:

Helper.helper.showAlert(title: "Not Internet Detected", msg: "Data Connectivity is Required", controller: self)

但是在类里面我得到一个错误:

showAlert(title: "Email in use, did you use another method to register", msg: "please try again", controller: self)

我得到的错误是:

Cannot convert value of type Helper to expected type UIViewController

如何解决这个问题?谢谢!

最佳答案

您必须传递一个 UIViewController 实例作为第三个参数。 Helper 类中的 selfHelper 而不是 UIViewController。这就是编译器所提示的。警报只能从 View Controller 中呈现。

考虑使用UIViewController的扩展

extension UIViewController {

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

您可以在任何继承自 UIViewController 的类中调用该方法。

关于ios - UIAlertController 在 Swift 3.0 中使用辅助类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43986562/

相关文章:

快速编程 NSErrorPointer 错误等

ios - 从 UICollectionViewCell 呈现 AlertView

swift - 关闭 UIAlertController UITextField 上的键盘

ios - 如何动态管理iOS自动续订订阅?

iphone - IOS rss 订阅登录

swift - 如何快速检查两个实例是否为同一类/类型

ios - 如何在 iOS 中创建类似 UIActionSheet 背景 View 的 View ?

ios - 使用信号量从 Parse 返回图像

ios - 我应该在哪里声明我的修改标识符?

ios - 如何从代表的 Collection View 单元格中获取 indexPath 项?