问题
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