iOS:警告“尝试呈现其视图不在窗口层次结构中的ViewController”
当我尝试在导航控制器上显示一个ActivityController时,我收到以下警告,
Attempt to present <UIActivityViewController: 0x15be1d60> on <UINavigationController: 0x14608e80> whose view is not in the window hierarchy!
我试图通过下面的代码呈现视图控制器,
UIActivityViewController * activityController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:applicationActivities]; activityController.excludedActivityTypes = excludeActivities; UIViewController *vc = self.view.window.rootViewController; [vc presentViewController: activityController animated: YES completion:nil]; [activityController setCompletionHandler:^(NSString *activityType, BOOL completed) { NSLog(@"completed"); }];
这里怎么了?
你正试图从rootViewController
提供一个视图控制器。 在你的情况下,我认为rootViewController
不是当前的ViewController。 要么你提出或推动了一个新的UIViewController
的顶部。 你应该从最顶层的视图控制器本身提供一个视图控制器。
你需要改变:
UIViewController *vc = self.view.window.rootViewController; [vc presentViewController: activityController animated: YES completion:nil];
至:
[self presentViewController: activityController animated: YES completion:nil];
分析:因为目前的模态视图ViewController类没有被加载到窗口中。 这相当于build筑物,二楼还没build好,直接去盖三层,这绝对不是。 只有在加载ViewController的视图之后;
python
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self showAlertViewController]; } - (void)showAlertViewController { UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hello world" message:@"(*  ̄3)(ε ̄ *)d" preferredStyle:UIAlertControllerStyleAlert]; // Create the actions. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"hello" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"The \"Okay/Cancel\" alert's cancel action occured."); }]; UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"world" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { NSLog(@"The \"Okay/Cancel\" alert's other action occured."); }]; // Add the actions. [alertController addAction:cancelAction]; [alertController addAction:otherAction]; UIWindow *windows = [[UIApplication sharedApplication].delegate window]; UIViewController *vc = windows.rootViewController; [vc presentViewController:alertController animated: YES completion:nil]; }
这对我有效。
replace行:
UIViewController *vc = self.view.window.rootViewController; [vc presentViewController: activityController animated: YES completion:nil]; //to [self presentViewController:activityController animated: YES completion:nil];
要么
[self.navigationController pushViewController:activityController animated:YES];
我遇到了iPhone 6+中的类似问题。
在Swift 2.0中
let obj = self.storyboard?.instantiateViewControllerWithIdentifier("navChatController") as! UINavigationController obj.modalPresentationStyle = .FormSheet obj.modalTransitionStyle = .CoverVertical Constants.APPDELEGATE.window?.rootViewController?.presentViewController(obj, animated: false, completion: nil)
我这样解决了