Draven Zuo
Draven Zuo

Reputation: 111

How to get notification when a view controller pop or push in to the navigation controller stack

I want to get notification when a view controller pop or push in the navigation controller stack. I tried to use

- (void)setViewControllers:(NSArray *)viewControllers

But I failed. And I do not want to use delegate method to achieve this...

Upvotes: 6

Views: 3943

Answers (2)

Draven Zuo
Draven Zuo

Reputation: 111

I use UINavigationControllerDelegate method to solve this problem.

- (void)navigationController:(UINavigationController *)navigationController
      willShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated

Upvotes: 4

in.disee
in.disee

Reputation: 1112

You can subclass UINavigationController and override some methods:

- (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];
}

i left user info like @{}, but you can place there something if You want, like controller that was added or removed.

I don't know, but I think You should think twice, if You architecture need notifications for such situation.

Also You have to check does pop methods call each other, in such situation you can get few notifications for one pop.

Upvotes: 4

Related Questions