从自定义类中显示alertController

我试图从我所做的类中显示一个AlertController。 由于AlertController是UIResponder的一个子类,我正在使用Xcode提示我的以下代码行

superclass?.presentViewController(alertController, animated: true, completion: nil) 

但是我不能编译,因为AnyClass? 没有任何成员presentViewController。 我的类是NSObject的一个子类。

任何其他解决scheme 谢谢

那么你只需要find最顶层的视图控制器,并从那里呈现alertcontroller

 UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController; while (topController.presentedViewController) { topController = topController.presentedViewController; } [topController presentViewController:alertController animated:YES completion:nil]; 

学分

注意:这是代码的objective-c版本。 请把它转换成相应的快速。

迅速

 let topController = UIApplication.sharedApplication().keyWindow!.rootViewController as UIViewController while (topController.presentedViewController) { topController = topController.presentedViewController; } topController.presentViewController(alertController, animated:true, completion:nil) 

问题是你对“来自”的理解。 警报出现在界面的某个视图前面。 因此,我们需要知道什么观点。 答案是:某个视图控制器的主视图 – 主视图在界面中的视图控制器。

因此,只有主视图在界面中的视图控制器可以被告知呈现警报。 这是您必须提供“视图”的视图控制器。

您需要从某处获取对该视图控制器的引用,以便您的代码可以告诉视图控制器显示该警报。 这本身可能是一个有趣的问题; 的确,“获得对现有对象的引用”是cocoa编程艺术的主要部分。

从你的视图控制器你有通过控制器的引用,消息,标题如

 Settings.getAlertViewConroller(self, DialogTitle: "Test Sale", strDialogMessege: "You are performing a test sale. This is not a real transaction.") 

其中Setting是NSObject的子类。在设置类中,你必须定义方法为

 class func getAlertViewConroller(globleAlert:UIViewController,DialogTitle:NSString,strDialogMessege:NSString){ let actionSheetController: UIAlertController = UIAlertController(title: DialogTitle, message: strDialogMessege, preferredStyle: .Alert) let nextAction: UIAlertAction = UIAlertAction(title: "OK", style: .Default) { action -> Void in } actionSheetController.addAction(nextAction) globleAlert.presentViewController(actionSheetController, animated: true, completion:nil) } 

即呈现UIAlertController。

最新Swift:

  var topController:UIViewController = UIApplication.shared.keyWindow!.rootViewController! while ((topController.presentedViewController) != nil) { topController = topController.presentedViewController!; } topController.present(alertController, animated:true, completion:nil)