views:

395

answers:

1

quick question - I have my "first view" which is going to be the ONLY view in my application. I've added a UITabBar to this view using Interface Builder. I am simply wanting to use this as a menu to control the contents of a scroll view.

For example, the user clicks on the first icon in the UITabBar - I get its tag, then based on that, will add a subview to the scrollview. This is working ok....

...but, I have been viewing a few tutorials on tabbars and it seems that 99% of the time they are used to control views. I simply want it to return my tags.

So my question is this: is what I am doing ok?? Can it be used for simply returning a value rather than changing a view? If this is common/OK practice, how on earth do I reference it?

I can get the selected item tag, but cannot actually reference the uiTabBar to make the first button selected. In my .h file, I tried to specify an IBOutlet for the controller, but I cannot link this in IB.

thanks for any info!

A: 

To receive notifications that a tab bar item has been clicked you need to modify your view controller to implement the UITabBarDelegate protocol and add an outlet for the tab bar. To do this, modify your declaration in MyViewController.h to something like this:

@interface MyViewController : UIViewController <UITabBarDelegate> {
    UITabBar *tabBar;
    ...
}

@property (nonatomic, assign) IBOutlet UITabBar *tabBar;

Then implement the tabBar:didSelectItem method in MyViewController.m as follows:

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    NSLog(@"Tab clicked: %d", item.tag);
}

You must also set your view controller as the delegate of the tab bar in IB. (hint: connect up the 'delegate' outlet from the tab bar to File's Owner).

To access the tab bar from your view controller use the tabBar property and do things like:

self.tabBar.selectedItem = [self.tabBar.items objectAtIndex:0];

As to whether this is a good idea - why not? All the tutorials show a tab bar being used with a UITabBarContoller to switch views, but it is designed to operate as a stand-alone control as well. As long as you are not breaking any HIG rules then how you implement your interface switching is up to you.

Robin Summerhill
worked like a charm - thank you! It was the objectAtIndex which was causing it to fail. I'd also tried the UITabBarDelegate line, but had removed it. Thanks very much :)
Matt Facer