0

我有两个视图控制器,都在导航控制器内。父控制器是一个表视图,我为表视图正确设置了委派。当我在父视图控制器上点击一行时,我希望子控制器出现。这有效,即出现子视图控制器,并且我在子控制器上有一个“后退”导航按钮。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Create and push another view controller.
    ChildVC *detailVC = [[ChildVC alloc] initWithNibName:@"ChildVC" bundle:nil];

    // When user dismisses child controller do this...
    [detailVC setDismissBlock:^{
        NSLog(@"Dismiss block called");
    }];

    // Setup navigation
    [self.navigationController pushViewController:detailVC animated:YES];
}

在 ChildVC.h 我有

@interface ChildVC : UIViewController
@property (nonatomic, copy) void (^dismissBlock)(void);
@end

在 ChildVC.m 我有以下尝试执行父控制器的解除块代码,但无济于事,即我没有看到 NSLog 执行。

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (![[self.navigationController viewControllers] containsObject:self]) {
        // We were removed from the navigation controller's view controller stack
        // thus, we can infer that the back button was pressed
        **// How do I call the presenting controller's dissmissBlock?**
        **// I tried the following to no avail, since presentingViewController is nil**
        [[self presentingViewController] dismissViewControllerAnimated:YES completion:_dismissBlock];
    }
}

如果使用解除块不是这里的机制,那是什么?谢谢!

4

1 回答 1

0

这是一种反模式,因为您的子视图控制器通常不应该对他们的父母一无所知...但是要解决您当前的问题-您在 viewWillDisappear 中调用了dismiss块-并测试您的视图控制器是否是仍在堆栈上将返回 YES - 因为视图尚未消失。

另一个问题是“后退”导航按钮,假设它是标准 UINavigationController 后退按钮,已经调用了 dismissViewControllerAnimated: 方法,因此即使您将其更改为 viewDidDisappear,当您调用“[self presentingViewController]”时,它也会为零。

听起来你想做这样的事情:

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (![[self.navigationController viewControllers] containsObject:self]) {
        if (_dismissBlock) _dismissBlock();
    }
}
于 2013-08-21T05:18:52.817 回答