显示来自viewDidLoad的警报消息

Shi*_*rra 13 xcode objective-c uialertview ios

我想从一个显示警报消息viewDidLoad()的方法,ViewController.m从替代viewDidAppear()方法.

这是我的代码:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

警告:试图提出<UIAlertController: 0x7fbc58448960><ViewController: 0x7fbc585a09d0>他们的看法是不是在窗口层次!

Woo*_*ock 22

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

如果你真的想要调用这个警报viewDidLoad你可以通过在这个GCD块中包装你的演示调用来引起轻微的延迟,等待下一个运行循环,但是我建议你不要(它很难看).

dispatch_async(dispatch_get_main_queue(), ^ {
    [self presentViewController:alert animated:YES completion:nil];
});
Run Code Online (Sandbox Code Playgroud)


Aka*_*ash 9

将此调用移至viewDidAppear:方法.