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

编程入门 行业动态 更新时间:2024-10-19 00:29:41
本文介绍了如何在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中显示来自另一个班级的警报?

本文发布于:2023-11-26 18:11:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警报   班级   如何在   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!