views:

511

answers:

1

I have this code - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item

What I am looking for is a code snippet that illustrates how to detect which button was pressed inside the delegate presumably using item.

So maybe I have buttons 1 - 4 lined up on the tabbar. My user presses the button position 2. I need to know that so I can bring up a view appropriate for that button.

I tried something like this but it is not working.

NSInteger *barIndex = [[barTab items] IndexofObject:item];

If someone could provide some working example code that would be great.

Thanks in advance.

+1  A: 

when you create your UITabBarItems you'll want to give them each a specific tag. When your - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item method is called, read the tag number out.

NSInteger tag = item.tag;

Using the index of the item is not appropriate for tab bars, since the user can change the order of the tabs.


And good practice is to use an enum for each of your tags, so that you don't have a bunch of "random" numbers scattered throughout your code.

typdef enum {
  JPButton1,
  JPButton2,
  JPButton3
} JPButtonType

and then in your tabBar:didSelectItem: method you can test the tags like so:

if (item.tag == JPButton1) {
  // do some stuff with button one here
}
kubi
Thank you! It worked perfectly.
jp chance
careful with my syntax on the addition. i don't have any compilers handy, so I'm not 100% that it's correct, but it should be plenty close.
kubi