views:

379

answers:

1

I am switching tabs through code with this:

self.tabBarController.selectedIndex = 1; // or any other number

The switching between the tabs works fine. I'm wondering if there is a way to animate the transition. It'd have to be only in this instance, not the total tabbarcontroller in general. That is to say that the transition will only take place when the tab is switched through that specific piece of code. It should be instantaneous(without animation) when the actual tab item is clicked.

If anyone can help, help is much appreciated.

+1  A: 

If you don't have anything complicated going on with the tab bar controller, you can roll your own from a UITabBar and then you can do anything you want when you switch tabs. You just implement the UITabBarDelegate. Here is example code slightly modified from what I'm using in an app:

.h file:

@interface AllGames : UIViewController <UITabBarDelegate> {
    IBOutlet UITabBar *tabBar;
}
@property (nonatomic, retain) IBOutlet UITabBar *tabBar;

.m file:

@implementation AllGames

@synthesize tabBar;

UIViewController *subviews[3];

- (void)viewDidLoad {
    [super viewDidLoad];

    int startTab = [Preferences LookupPreferenceInt:CFSTR("GameTab")];
    [tabBar setSelectedItem:[tabBar.items objectAtIndex:startTab]];

    Games1 *vc1 = [[Games1 alloc] initWithNibName:@"Games1" bundle:nil];
    Games2 *vc2 = [[Games2 alloc] initWithNibName:@"Games2" bundle:nil];
    Games3 *vc3 = [[Games3 alloc] initWithNibName:@"Games3" bundle:nil];

    subviews[0] = vc1;
    subviews[1] = vc2;
    subviews[2] = vc3;
    vc1.view.alpha = 0;
    vc2.view.alpha = 0;
    vc3.view.alpha = 0;
    [self.view addSubview:vc1.view];
    [self.view addSubview:vc2.view];
    [self.view addSubview:vc3.view];
    subviews[startTab].view.alpha = 1.0;
}

- (void)dealloc {
    [Preferences StorePreferenceInt:CFSTR("GameTab") withValue:[tabBar selectedItem].tag-1];
    for (int x = 0; x < 3; x++)
    {
        [subviews[x].view removeFromSuperview];
        [subviews[x] release];
        subviews[x] = 0;
    }
    [super dealloc];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    printf("Hit item tag: %d\n", item.tag);
    for (int x = 1; x <= 3; x++)
    {
        subviews[x-1].view.alpha = (x == item.tag)?1.0:0.0;
    }
}

Inside didSelectItem you can do any animation you want. I just do an immediate swap of the alpha, but you can be as complicated as you want.

Nathan S.
Do you have any examples? It'd help me to get an idea of what to do.
intl
Edited the above code with a detailed example.
Nathan S.