【发布时间】:2016-10-13 07:47:31
【问题描述】:
我有一个主类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 在这里不起作用,并且给了我一个错误。我如何引用当前打开的视图控制器(即AddFriendsController 在这种情况下),因为我希望在许多不同的 swift 文件中使用相同的方法?
谢谢。
【问题讨论】:
-
创建扩展 showMessage 。作为扩展 ErrorReporting 。然后是你的函数。
-
@sourav 你能详细解释一下吗?还在快速学习...
-
extension ErrorReporting { func showMessage(title: String, msg: String) { let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: “好的”,样式:UIAlertActionStyle.Default,处理程序:nil)) self.presentViewController(alert, animated: true, completion: nil) } }
标签: swift uiviewcontroller uialertcontroller swift2.3