1

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"])
     {
     }
 }
Voloda2
  • 12,359
  • 18
  • 80
  • 130
  • This doesn't answer your question directly, but is there a reason you can't instead declare yourself as the UITabBarController's delegate and implement "tabBarController:didSelectViewController:" to respond to selected view controller changes? – nickbona Feb 15 '12 at 14:20
  • Well, for one, it "is not called when your code changes the tab bar contents programmatically". It would be convenient not to have to handle that separately. – c roald Jul 29 '13 at 19:33

1 Answers1

4

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.

erikprice
  • 6,240
  • 3
  • 30
  • 40
  • Note: changing tabs programmatically seems NOT to cause the KVO notification to be fired, either. – c roald Jul 29 '13 at 19:37
  • @croald That's pretty standard. KVO notifications are not fired for many UIKit view/view controller properties when the property is modified programmatically. Generally, it's because you already know that the property is being modified. It's a pain sometimes, but it does prevent certain kinds of feedback loops. – erikprice Jul 30 '13 at 18:35