Search code examples
iosuitabbarcontrollerkey-value-observing

I didn't get any notifications when I touched on tabbar items


I have UITabbarCoo=ntroller application. I added an observer and I'm waiting for any notifications. I didn't get any notifications when I touched on tabbar items.

[self.tabBarController addObserver:self forKeyPath:@"selectedIndex" options:NSKeyValueObservingOptionNew context:@"changedTabbarIndex"];

 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
 NSString *action = (NSString*)context; 
 if([action isEqualToString:@"changedTabbarIndex"])
     {
     }
 }

Solution

  • I noticed the same thing. I assume that this is a bug in the UITabBarController implementation. Note that using a key path of selectedViewController instead of selectedIndex does cause KVO notifications to be fired.

    But be careful. If your UITabBarController has a UIMoreNavigationController (for the "More" tab), you will get the KVO notification when the user selects the "More" tab, but you won't get any notifications when the user selects a child viewcontroller of the UIMoreNavigationController. This is because the UIMoreNavigationController is a separate view controller, so when you select one of its child view controllers, the UITabBarController's selectedViewController isn't changing – it's actually the UIMoreNavigationController's topViewController that changes.

    It would be great if you could then observe the UIMoreNavigationController's topViewController property in addition to the UITabBarController's selectedViewController property, but this property does not appear to cause KVO notifications to be fired either. However, you can set a delegate on the UIMoreNavigationController and implement the navigationController:didShowViewController:animated: method.

    Summary: observe the selectedViewController property of the UITabBarController, and if your application has a "More" tab, set a delegate on the tab bar controller's moreNavigationController property.