Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

iphone - UITabBar(Controller) - Get index of tapped?

I've got a tab bar application and I need to know when and what button a user taps on the tab bar as to display the appropriate notifications and such.

In short: How would I go about detecting the index of a tapped UITabBarItem on a UITabBar?

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The answer depends on whether or not the UITabBar is managed by a UITabBarController or not.

Case 1 - UITabBar is already handled by a UITabBarController

Implement the UITabBarControllerDelegate protocol. Specifically the tabBarContoller:didSelectViewController: method. Set an instance of your class that implements the protocol as the delegate of the UITabBarController.

- (void)tabBarController:(UITabBarController *)theTabBarController didSelectViewController:(UIViewController *)viewController {
    NSUInteger indexOfTab = [theTabBarController.viewControllers indexOfObject:viewController];
    NSLog(@"Tab index = %u (%u)", (int)indexOfTab);
}

In this case you have to be aware of the special situation where you have enough controllers in the tab controller to cause the "More" tab to be displayed. In that case you'll receive a call to the tabBarController:didSelectViewController: with a view controller that isn't in the list (it's an instance of an internal UIKit class UIMoreNavigationController). In that case the indexOfTab in my sample will be NSNotFound.

Case 2 - UITabBar is NOT already handled by a UITabBarController

Implement the UITabBarDelegate protocol. Specifically the tabBar:didSelectItem: method. Set an instance of your class that implements the protocol as the delegate of the UITabBar.

- (void)tabBar:(UITabBar *)theTabBar didSelectItem:(UITabBarItem *)item {
    NSUInteger indexOfTab = [[theTabBar items] indexOfObject:item];
    NSLog(@"Tab index = %u", (int)indexOfTab);
}

EDIT: Modified the method parameter variables to eliminate the OP's compilation warning about tabBarController being hidden.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...