问题描述
我想显示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];
}
我收到此错误:
推荐答案
确定不是错误,问题在于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的警报消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!