从自定义类中显示alertController

时间:2015-01-01 21:57:01

标签: ios swift alert nsobject uialertcontroller

我正在尝试从我制作的类中显示AlertController。 由于AlertController是UIResponder的子类,我使用Xcode建议我的以下代码行

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

但我无法编译,因为AnyClass?没有任何成员presentViewController。 我的类是NSObject的子类。

还有其他解决方案吗? 感谢

4 个答案:

答案 0 :(得分:6)

您只需要找到最顶层的视图控制器并从那里显示alertcontroller

UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

while (topController.presentedViewController) {
    topController = topController.presentedViewController;
}
[topController presentViewController:alertController animated:YES completion:nil];

credits

注意:这是代码的Objective-c版本。请相应地将其转换为swift。

<强> SWIFT

let topController = UIApplication.sharedApplication().keyWindow!.rootViewController as UIViewController

while (topController.presentedViewController) {
    topController = topController.presentedViewController;
}
topController.presentViewController(alertController, animated:true, completion:nil)

答案 1 :(得分:1)

问题是你对“来自”的理解。界面中某些视图前面会显示警报。因此,我们需要知道什么视图。答案是:一些视图控制器的主视图 - 一个视图控制器,其主视图位于界面中。

因此,只有主视图在界面中的视图控制器才能被告知呈现警报。您必须提供“来自”的视图控制器。

您需要有一些方法可以从代码的任何位置获取对该视图控制器的引用,以便您的代码可以告诉该视图控制器显示警报。这本身就是一个有趣的问题;实际上,“获取对现有对象的引用”是Cocoa编程艺术的主要部分。

答案 2 :(得分:1)

从你的视图控制器你已经传递了控制器的参考,消息,标题,如

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。

答案 3 :(得分:0)

最新的斯威夫特:

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