我有两个视图控制器,都在导航控制器内。父控制器是一个表视图,我为表视图正确设置了委托。当我在父视图控制器上点击一行时,我想要显示子控制器。这是有效的,即子视图控制器出现,我在子控制器上有一个“后退”导航按钮。
- (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];
}
}
如果使用dismiss block不是这里的机制,那是什么?谢谢!
答案 0 :(得分:0)
这是一种反模式,因为你的儿童视图控制器一般都不应该对他们的父母一无所知......但要解决你当前的问题 - 你在viewWillDisappear中调用dismiss块 - 并测试你的是否是你的视图控制器仍然在堆栈上将返回YES - 因为视图尚未消失。
另一个问题是'back'导航按钮,假设它是标准的UINavigationController后退按钮,已经调用了dismissViewControllerAnimated:方法,所以即使你把它改为viewDidDisappear,当你调用`[self presentingViewController]时“它将是零。
听起来你想做这样的事情:
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
if (![[self.navigationController viewControllers] containsObject:self]) {
if (_dismissBlock) _dismissBlock();
}
}