presentViewController not working in viewDidLoad

∥☆過路亽.° 提交于 2019-12-13 06:55:36

问题


In this code the alert action is shown every time the app become active:

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(applicationDidBecomeActive:)
                                             name:UIApplicationDidBecomeActiveNotification
                                           object:nil];


}


- (void)applicationDidBecomeActive:(NSNotification *)notification
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Please make your choice"
                                                                         message:@"Would you like a cup of coffee?"
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"YES"
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction *action) {
                                                      NSLog(@"You tapped YES");
                                                  }];

    UIAlertAction *maybeAction = [UIAlertAction actionWithTitle:@"MAYBE"
                                                      style:UIAlertActionStyleDefault
                                                    handler:^(UIAlertAction *action) {
                                                        NSLog(@"You tapped MAYBE");
                                                    }];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel"
                                                       style:UIAlertActionStyleCancel
                                                     handler:nil];

    [alertController addAction:yesAction];
    [alertController addAction:maybeAction];
    [alertController addAction:cancelAction];

    [self presentViewController:alertController animated:YES completion:nil];
}

Also, everything works as expected if I move the code block of the UIAlertController in viewDidAppear method.

But if I move the UIAlertController in viewDidLoad :

- (void)viewDidLoad {
    UIAlertController *alertController [...]
    [...]
    [self presentViewController:alertController animated:YES completion:nil];
}

it doesn't works. The alert is not shown.


回答1:


In viewDidLoad it is not part of the view hierarchy at that time hence it is silently ignored, on viewWillAppear at this time the view hierarchy is already set up hence the reason it works.



来源:https://stackoverflow.com/questions/26978487/presentviewcontroller-not-working-in-viewdidload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!