我读了this post和this one关于如何在UIViewController子类之外调用presentViewController表单。在我的例子中,自定义类是NSObject的子类。以下方法是唯一有效的方法(从我读过的例子中):
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
我的问题:是否有一个更好的解决方案,不依赖于appDelegate(因为我知道这种方法在设计方面不是很整洁)......
答案 0 :(得分:9)
我有时会创建一个实用程序类来显示警报等。我通常做的是让我的方法呈现视图控制器将当前视图控制器作为参数。这种方法效果很好。
以下是我的一个项目中的文件Utils.swift的示例方法。它定义了一个在当前视图控制器上显示UIAlertController警报的类函数:
class Utils
{
static let sharedUtils = Utils()
class func showAlertOnVC(
targetVC: UIViewController,
var title: String,
var message: String)
{
title = NSLocalizedString(title, comment: "")
message = NSLocalizedString(message, comment: "")
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.presentViewController(alert, animated: true, completion: nil)
}
}
上面的代码定义了一个类Utils。请注意,它没有任何基类,在Swift中是OK。
接下来,它定义了一个公共静态变量sharedUtils,您可以使用它来访问singleton Utils类。
最后,它定义了一个类方法showAlertOnVC
,可用于在当前视图控制器之上显示UIAlertController警报。要使用showAlertOnVC
,请从当前视图控制器中调用它,并将self作为targetVC
参数传递。
答案 1 :(得分:2)
我认为这是最简单的解决方案:
class Utils {
static func displayTheAlert(targetVC: UIViewController, title: String, message: String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "OK", style: .Default, handler: {(action) -> Void in
})))
targetVC.presentViewController(alert, animated: true, completion: nil)
}
}
//然后调用它
Utils.displayTheAlert(self, title: "Fout", message: "Uw bestelling is nog niet klaar")
答案 2 :(得分:2)
从View的设计角度来看,模型类(NSObject)不建议直接与View交互。它不符合MVC模式。避免在NSObject类中使用UIKIT。