UIAlertController 根本没有出现

UIAlertController not appearing at all

我正在尝试将 UIAlertController 添加到我的应用程序,但它根本没有出现。我尝试了以下方法:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Message" message:@"Web Service is not available." preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];

[self presentViewController:alertController animated:YES completion:nil];

但这根本没有出现,我做错了什么?

在故事板的初始视图控制器中,它必须在 viewDidAppear: 中。否则,如果在 XIB 中使用,它还会在 viewWillAppearviewDidLoad.

中显示警报

我 运行 您在 iOS 8 和 9 的单视图应用程序模板中的代码,将您的代码放入给定的 ViewController, 以下视图生命周期回调中:

  • viewDidAppear - 成功
  • viewWillAppear - 未显示警报;在控制台中导致此输出:警告:尝试呈现其视图不在 window 层次结构中!
  • viewDidLoad - 未显示警报;在控制台中导致此输出:不允许在解除分配时尝试加载视图控制器的视图,这可能会导致未定义的行为 ()。
- (void)showMessage:(BOOL)animated {

UIAlertController *alertController = [UIAlertController  alertControllerWithTitle:@"Do not leave any Field Empty"  message:nil  preferredStyle:UIAlertControllerStyleAlert];

[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    [self dismissViewControllerAnimated:YES completion:nil];
}]];
[self present:alertController animated:YES completion:nil];

}

我在哪里调用这个方法

        [self showMessage:YES];

效果很好,可能有人会受益。