14

I have created a UITabBar and UITabBarItems without UITabBarController on it, now i want to know how to place an action on click of the UITabBarItem.What is the method i should use for action on UITabBarItem?

suse
  • 10,503
  • 23
  • 79
  • 113
  • According to the Human Interface Guidelines, tab bars are for switching views. Are you sure you don't want to use a tool bar? – Frank Schmitt Mar 26 '10 at 00:24

4 Answers4

23

You can't set an action on a UITabBarItem object directly. Instead, your view controller should implement the following UITabBarDelegate method:

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;

This method is called when the user selects a tab (i.e. UITabBarItem).

Shaggy Frog
  • 27,575
  • 16
  • 91
  • 128
2

Are you using a UINavigationController? If so, from the active view controller subclass you get the navigationItem and add the buttons to it, e.g.:

- (void) viewWillAppear:(BOOL)animated;
{
    [super viewWillAppear: animated];
    UIBarButtonItem * leftButtonItem = [[[UIBarButtonItem alloc] initWithTitle: @"Don't Show Again" style: UIBarButtonItemStyleBordered target: self action: @selector(permanentlyCloseWelcomeView)] autorelease];
    [[self navigationItem] setLeftBarButtonItem: leftButtonItem];
}
xyzzycoder
  • 1,831
  • 13
  • 19
1

Can you get away with using instances of UIToolbar and UIBarButtonItem instead? It could be more straightforward.

toolBar = [[UIToolbar alloc] init];
newPlayerItem = [[UIBarButtonItem alloc] initWithTitle:@"+"
                                    style:UIBarButtonItemStyleBordered
                                    target:self
                                    action:@selector(newPlayer:)];

NSArray *toolBarItemsArray = [[NSArray alloc] initWithObjects:newPlayerItem, nil];
[toolBar setItems:toolBarItemsArray];
[toolBarItemsArray release];
sth
  • 222,467
  • 53
  • 283
  • 367
Ken
  • 30,811
  • 34
  • 116
  • 155
-2

There is a better method than didSelectItem: for each TabBarItem you create an action:
[item1 setAction:@selector(pressItem1:)];
[item2 setAction:@selector(pressItem2:)];
[item3 setAction:@selector(pressItem3:)];
[item4 setAction:@selector(pressItem4:)];
and then you can use the new actions:

-(void)pressItem1:(UITabBarItem *) item1 {<br/>
    // Here comes your code which<br/>
    // occurs after pressing item1.<br/>
}

That works for me

Andy Obusek
  • 12,614
  • 4
  • 41
  • 62
wesimaster
  • 21
  • 1