我是swift3的新手。现在,我正在寻找一种从其他swift.file
调用alert函数的方法像这样:
//MainView.swift
//Call function
AlertFun.ShowAlert(title: "Title", message: "message..." )
//Another page for storing functions
//Function.swift
public class AlertFun {
class func ShowAlert(title: String, message: String ) {
let alert = UIAlertController(title: tile, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
这里的问题......不能这样做......
self.present(alert, animated: true, completion: nil)
我该如何实施?感谢。
答案 0 :(得分:5)
将viewController引用作为参数传递给showAlert函数,如:
//MainView.swift
//Call function
AlertFun.ShowAlert(title: "Title", message: "message...", in: self)
//Another page for storing functions
//Function.swift
public class AlertFun {
class func ShowAlert(title: String, message: String, in vc: UIViewController) {
let alert = UIAlertController(title: tile, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
vc.present(alert, animated: true, completion: nil)
}
}
答案 1 :(得分:2)
您的控制器的调用方法
Utility.showAlertOnViewController(targetVC: self, title: "", message:"")
您的班级
class Utility: NSObject {
class func showAlertOnViewController(
targetVC: UIViewController,
title: String,
message: String)
{
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: UIAlertControllerStyle.alert)
let okButton = UIAlertAction(
title:"OK",
style: UIAlertActionStyle.default,
handler:
{
(alert: UIAlertAction!) in
})
alert.addAction(okButton)
targetVC.present(alert, animated: true, completion: nil)
}
}
答案 2 :(得分:0)
我发现我看到的所有示例都不会在没有警告的情况下起作用:
尝试在视图不在窗口层次结构中的
<UIAlertController: 0x7f82d8825400>
上显示<app name>
!
对我有用的代码如下。函数调用与以前一样:
AlertFun.ShowAlert(title: "Title", message: "message...", in: self)
但是,要使其正常工作,Function.swift
文件必须在DispatchQueue.main.async
内部显示警报。因此Function.swift
文件应如下所示:
public class AlertFun
{
class func ShowAlert(title: String, message: String, in vc: UIViewController)
{
DispatchQueue.main.async
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
vc.present(alert, animated: true, completion: nil)
}
}
}