从viewDidLoad显示警报消息

我想显示从ViewController.m viewDidLoad()方法,而不是从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]; } 

我得到这个错误:

警告:尝试在<ViewController: 0x7fbc585a09d0>上呈现<UIAlertController: 0x7fbc58448960> ,其视图不在窗口层次中!

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

如果你真的想在viewDidLoad中调用这个alert,你可以通过在这个GCD块中包装你的演示文稿调用来引起稍微的延迟,等待下一个运行循环,但是我build议你不要(这很丑陋)。

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

将此调用移至viewDidAppear:方法。

您必须embedded导航控制器并显示控制器

 - (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.navigationController presentViewController:alert animated:NO completion:nil]; // [self presentViewController:cameraView animated:NO completion:nil]; //this will cause view is not in the window hierarchy error } 

要么

  [self.view addSubview:alert.view]; [self addChildViewController:alert]; [alert didMoveToParentViewController:self]; 

Swift 3 iOS 10中,我使用操作队列将更新UI的代码块放到主线程中。

 import UIKit class ViewController2: UIViewController { var opQueue = OperationQueue() override func viewDidLoad() { super.viewDidLoad() let alert = UIAlertController(title: "MESSAGE", message: "HELLO WORLD!", preferredStyle: UIAlertControllerStyle.alert) // add an action (button, we can add more than 1 buttons) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // show the alert self.opQueue.addOperation { // Put queue to the main thread which will update the UI OperationQueue.main.addOperation({ self.present(alert, animated: true, completion: nil) }) } } } 

总之我们正在使用asynchronous。 这使得警报消息按预期显示(即使我们在viewDidLoad()中)。