我想显示ViewController.m的viewDidLoad()方法而不是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的警报消息
发布评论