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

2023-11-25

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

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

然后我有这个ErrorReporting.swift file:

进口基金会

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在这里不起作用,并且给我一个错误。我如何引用当前打开的视图控制器(即AddFriendsController在这种情况下),因为我希望在许多不同的 swift 文件中使用相同的方法?

Thanks.


您可以为 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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Swift 中显示来自另一个类的警报? 的相关文章

随机推荐