显示来自viewDidLoad的警报消息 [英] Display Alert Message from viewDidLoad

查看:87
本文介绍了显示来自viewDidLoad的警报消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示ViewController.mviewDidLoad()方法而不是viewDidAppear()方法的警报消息.

I want to display a alert message from viewDidLoad() method of ViewController.m instead from viewDidAppear() method.

这是我的代码:

- (void)viewDidLoad {
    [super viewDidLoad];

    //A SIMPLE ALERT DIALOG
    UIAlertController *alert =   [UIAlertController
                              alertControllerWithTitle:@"My Title"
                              message:@"Enter User Credentials"
                              preferredStyle:UIAlertControllerStyleAlert];


    UIAlertAction *cancelAction = [UIAlertAction
                               actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel action")
                               style:UIAlertActionStyleCancel
                               handler:^(UIAlertAction *action)
                               {
                                   NSLog(@"Cancel action");
                               }];

    UIAlertAction *okAction = [UIAlertAction
                           actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                           style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction *action)
                           {
                               NSLog(@"OK action");
                           }];

    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

我收到此错误:

警告:尝试在视图不在窗口层次结构中的<ViewController: 0x7fbc585a09d0>上显示<UIAlertController: 0x7fbc58448960>

推荐答案

确定不是错误,问题在于viewDidLoad中的视图层次结构未完全设置.如果使用viewDidAppear,则将设置层次结构.

OK not a bug, the issue is that in viewDidLoad the view hierarchy is not fully set. If you use viewDidAppear, then the hierarchy is set.

如果您确实要在viewDidLoad中调用此警报,可以通过将演示文稿调用包装在此GCD块中以引起轻微的延迟,等待下一个运行循环来执行此操作,但是我建议您不要t(很丑).

If you really want to call this alert in viewDidLoad you can do so by wrapping your presentation call in this GCD block to cause a slight delay, waiting for the next run loop, however I suggest you don't (it's ugly).

dispatch_async(dispatch_get_main_queue(), ^ {
    [self presentViewController:alert animated:YES completion:nil];
});

这篇关于显示来自viewDidLoad的警报消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆