IOS 上的 parentViewController return 为空

parentViewController return null on IOS

我正在使用此代码以模态方式呈现视图控制器:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SubmitAYoNViewController *ivc = [storyboard instantiateViewControllerWithIdentifier:@"SubmitAYoN"];
    [ivc setModalPresentationStyle:UIModalPresentationFullScreen];
    [self presentViewController:ivc animated:YES completion:nil];

然后在我的 SubmitAYoNViewController 中我有这个:

  NSLog(@"%@",self.parentViewController);
    if([self.parentViewController isKindOfClass:[YesOrNoViewController class]]) {
        NSLog(@"do something");
}

self.parentVeiwController 为 NULL。这是为什么?

编辑:我想从我的父视图控制器访问一个方法,然后是打开 SubmitAYoN 的方法。

解决方案:我改为使用委托。根据以下答案,presentViewController 不会创建父子关系。

self.parentViewController 是您从这个 viewcontrollerself.navigationgtionController

中呈现的东西

因此,当您展示 viewcontroller 时,您持有 `viewcontroller' 的实例将具有 self.parentViewController.

如果你想要呈现视图控制器,那么使用self.presentingViewControllerself.parentViewController returns 控制器父级,当它不是另一个控制器的子级时将为 nil。

所以使用:

NSLog(@"%@",self.presentingViewController);
if([self.presentingViewController isKindOfClass:[YesOrNoViewController class]]) {
   NSLog(@"do something");
}

来自 presentViewController:

的文档

This method sets the presentedViewController property to the specified view controller, resizes that view controller's view based on the presentation style and then adds the view to the view hierarchy.

因此没有提及将控制器设为子控制器,因为它是添加到现有视图层次结构中的视图。

在 iOS5 之前你会没事的。 属性 parentViewController 的文档指出:

Prior to iOS 5.0, if a view did not have a parent view controller and was being presented, the presenting view controller would be returned. On iOS 5, this behavior no longer occurs. Instead, use the presentingViewController property to access the presenting view controller.