如何在没有视图控制器的情况下显示UIAlertController?

如何在没有视图控制器的情况下显示UIAlertController?

场景:用户点击视图控制器上的按钮。视图控制器是导航堆栈中的最顶层(显然)。TAP调用另一个类上调用的实用程序类方法。在那里发生了一件坏事,我想在控件返回到视图控制器之前在那里显示一个警告。

+ (void)myUtilityMethod {
    // do stuff
    // something bad happened, display an alert.}

这是有可能的UIAlertView(但可能不太恰当)。

在这种情况下,您如何表示UIAlertController,就在那里myUtilityMethod?


PIPIONE
浏览 1082回答 3
3回答

BIG阳

您可以使用SWIFT 2.2执行以下操作:let alertController: UIAlertController = ...UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)以及SWIFT 3.0:let alertController: UIAlertController = ...UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)

梵蒂冈之花

斯威夫特let alertController = UIAlertController(title: "title", message: "message", preferredStyle: .alert)//...var rootViewController = UIApplication.shared.keyWindow?.rootViewControllerif let navigationController = rootViewController as? UINavigationController {     rootViewController = navigationController.viewControllers.first}if let tabBarController = rootViewController as? UITabBarController {     rootViewController = tabBarController.selectedViewController}//...rootViewController?.present(alertController, animated: true, completion: nil)目标-CUIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];//...id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;if([rootViewController isKindOfClass:[UINavigationController class]]){     rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;}if([rootViewController isKindOfClass:[UITabBarController class]]){     rootViewController = ((UITabBarController *)rootViewController).selectedViewController;}//...[rootViewController presentViewController:alertController animated:YES completion:nil];
打开App,查看更多内容
随时随地看视频慕课网APP