如何在视图控制器弹出或推入导航控制器堆栈时获得通知

Dra*_*Zuo 6 navigation stack uinavigationcontroller ios

我想在视图控制器弹出或推送导航控制器堆栈时收到通知。我试着用

- (void)setViewControllers:(NSArray *)viewControllers
Run Code Online (Sandbox Code Playgroud)

但我失败了。而且我不想使用委托方法来实现这一点......

in.*_*see 4

您可以子类化 UINavigationController 并重写一些方法:

- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"poped" object:nil userInfo:@{}];
    return [super popToRootViewControllerAnimated:animated];
}

- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"poped" object:nil userInfo:@{}];
    return [super popToViewController:viewController animated:animated];
}

- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"poped" object:nil userInfo:@{}];
    return [super popViewControllerAnimated:animated];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"pushed" object:nil userInfo:@{}];
    return [super pushViewController:viewController animated:animated];
}
Run Code Online (Sandbox Code Playgroud)

我留下了像@{}这样的用户信息,但是如果你愿意的话,你可以在那里放置一些东西,比如添加或删除的控制器。

我不知道,但我认为如果您的架构需要针对这种情况的通知,您应该三思而后行。

另外,您还必须检查 pop 方法是否相互调用,在这种情况下,您只能收到很少的一次 pop 通知。