1
votes

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.

3

3 Answers

5
votes

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
}
3
votes

I realize this question is quite old, but maybe this will help someone in the future:

The UITabBarController has a property called selectedIndex. For example, if the UITabBarController is declared as myTabBar, you can always get the currently selected tab index by calling

[myTabBar selectedIndex]

it will be equal to 0 for the first tab, 1 for the second, and so on...

1
votes

I know this post is over to years old now but you were on the right line instead of using

NSInteger *barItem = [[tabBar items] indexOfObject:item];

you need to use

int barItem = [[tabBar items] indexOfObject:item];

This is because

indexOfObject:item 

will return an int not an NSInteger.