swift - 如何在 Swift 中显示来自另一个类的警报?

标签 swift uiviewcontroller uialertcontroller swift2

我有一个主类 AddFriendsController,它运行以下代码行:

ErrorReporting.showMessage("Error", msg: "Could not add student to storage.")

然后我有了这个 ErrorReporting.swift 文件:

导入基金会

class ErrorReporting {
    func showMessage(title: String, msg: String) {
        let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

显然,self 在这里不起作用,并且给我一个错误。我如何引用当前打开的 View Controller (即在这种情况下 AddFriendsController),因为我希望在许多不同的 swift 文件中使用相同的方法?

谢谢。

最佳答案

您可以为 UIApplication 创建扩展方法(例如),它将返回您的 topViewController:

extension UIApplication {

    static func topViewController(base: UIViewController? = UIApplication.sharedApplication().delegate?.window??.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topViewController(nav.visibleViewController)
        }
        if let tab = base as? UITabBarController, selected = tab.selectedViewController {
            return topViewController(selected)
        }
        if let presented = base?.presentedViewController {
            return topViewController(presented)
        }

        return base
    }
}

然后你的类将如下所示:

class ErrorReporting {

    static func showMessage(title: String, msg: String) {
        let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
        UIApplication.topViewController()?.presentViewController(alert, animated: true, completion: nil)
    }
}

方法需要是static才能调用它作为ErrorReporting.showMessage

关于swift - 如何在 Swift 中显示来自另一个类的警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40015171/

相关文章:

ios - 为什么 UIView 的 CALayer.speed 为零会阻止 UIAlertController 的按钮工作?

ios - 函数中的 SceneKit 对象未出现在模拟器中

swift - 省略 Swift 闭包中的返回类型

ios - 从 UIViewController 呈现 UINavigationController

iphone - UITableView 问题 : Keep on getting this runtime error unrecognised selector

ios - 使用 UIAlertController 阻塞循环

ios - @IBAction 只是 Swift 中的一种语法,还是 @Something 在 Swift 中意味着特定的事物?

swift - 协议(protocol)之间的实现冲突

ios - 如何删除 UIViewController 类的 xib 文件?

xcode - UIAlertController 和堆叠式 UIAlert 按钮