iOS:警告"尝试呈现其视图不在窗口层次结构中的ViewController"

iOS*_*oob 39 objective-c ios uiview-hierarchy uiactivityviewcontroller presentviewcontroller

当我尝试在导航控制器上呈现ActivityController时,我收到以下警告,

Attempt to present <UIActivityViewController: 0x15be1d60> on <UINavigationController: 0x14608e80> whose view is not in the window hierarchy!
Run Code Online (Sandbox Code Playgroud)

我试图通过以下代码呈现视图控制器,

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");

    }];
Run Code Online (Sandbox Code Playgroud)

这里出了什么问题?

Mid*_* MP 34

您正试图从中呈现视图控制器rootViewController.在你的情况下,我认为rootViewController不是当前的ViewController.无论是你呈现还是推出了一个新UIViewController的.您应该从最顶层的视图控制器本身呈现视图控制器.

你需要改变:

UIViewController *vc = self.view.window.rootViewController;
[vc presentViewController: activityController animated: YES completion:nil];
Run Code Online (Sandbox Code Playgroud)

至:

[self presentViewController: activityController animated: YES completion:nil];
Run Code Online (Sandbox Code Playgroud)

  • 您可以移动方法以将另一个视图控制器调用到viewDidAppear: (3认同)
  • @TiagoAmaral:OP的问题不同,您的评论在当前上下文中无效.此外,如果您将该代码放在viewDidAppear中,则需要处理多种情况.viewWill/DidAppear方法将被多次调用(例如在一个presentViewController解散后,在一个警报解除后等).因此,如果将该代码放在viewDidAppear中,则需要处理这些情况. (2认同)

qin*_*ong 6

分析:因为目前的模态视图ViewController类还没有被加载到窗口中.这相当于建筑物,二楼还没有建成,直接去盖3楼,这绝对不是.只有在加载ViewController的视图后;

蟒蛇

- (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];
}
Run Code Online (Sandbox Code Playgroud)

这对我有用.