presentViewController无法在viewDidLoad中工作

时间:2014-11-17 17:36:00

标签: objective-c ios8 uialertcontroller

在此代码中,每次应用程序变为活动状态时都会显示警报操作:

- (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];
}

此外,如果我在 viewDidAppear 方法中移动UIAlertController的代码块,一切都会按预期工作。

但如果我在 viewDidLoad 中移动UIAlertController:

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

它不起作用。警报未显示。

1 个答案:

答案 0 :(得分:2)

在viewDidLoad中,它不是当时视图层次结构的一部分,因此它在viewWillAppear上被静默忽略,此时视图层次结构已经设置,因此它的工作原理。

相关问题