如何在Swift中显示来自另一个班级的警报? [英] How to show an alert from another class in Swift?
问题描述
我有一个主类AddFriendsController
,它运行以下代码行:
I have a main class, AddFriendsController
, that runs the following line of code:
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
在这里不起作用,给我一个错误.我希望在许多不同的swift文件中使用相同的方法,如何引用当前打开的视图控制器(在这种情况下为AddFriendsController
)?
Obviously, self
wouldn't work here, and is giving me an error. How can I refer to the currently open view controller (i.e. AddFriendsController
in this circumstance), as I am wishing to use this same method in many different swift files?
谢谢.
推荐答案
您可以为UIApplication创建扩展方法(例如),该方法将返回topViewController:
You can create extension method for UIApplication (for example) which will return your 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
}
}
然后您的课程将如下所示:
And then your class will look like this:
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
.
Method need to be static
to be able to call it as ErrorReporting.showMessage
.
这篇关于如何在Swift中显示来自另一个班级的警报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!