我是swift3的新手。现在,我正在寻找一种方法来调用警报函数从其他swift.file
:
//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)
我如何实现它?谢谢。
将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)
}
}
控制器的调用方法
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)
}
}
我发现,如果没有收到警告,我所见过的所有示例都无法正常工作:
尝试在视图不在窗口层次结构中的
<app name>
上显示<UIAlertController: 0x7f82d8825400>
!
为我工作的代码如下。函数调用和前面一样:
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)
}
}
}