天天看点

【iOS开发】---- UITabBarController的使用详解

定义两个控制器,已注上相应的解释:

//第一个控制器
    MyViewController *myVC = [[MyViewController alloc] init];
    UITabBarItem *firstItem = [[UITabBarItem alloc] initWithTitle:@"First" image:nil tag:1];
    //自定义样式
    [firstItem setFinishedSelectedImage:[UIImage imageNamed:@"home_o.png"]
            withFinishedUnselectedImage:[UIImage imageNamed:@"home.png"]];
    myVC.tabBarItem = firstItem;
    [firstItem release];
    
    
    //第二个控制器(带导航的)
    SecViewController *secVC = [[SecViewController alloc] init];
    secVC.navigationItem.title = @"Second View";
    
    //注意此处与第一个tabBarItem不同,是系统样式,系统提供了很多可供选择的样式
    UITabBarItem *secItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemHistory
                                                                       tag:2];
    //UITabBarItem右上角的数字标识
    secItem.badgeValue = @"3";
    
    secVC.tabBarItem = secItem;
    [secItem release];
    
    //将第二个控制器放在导航控制器中
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:secVC];
           

将上面个两个控制放如tabBarController中,tabBarController作为window的根控制器:

tabBarController = [[UITabBarController alloc] init];
    tabBarController.viewControllers = [NSArray arrayWithObjects:myVC,nav, nil];
    //默认设置选中第二个控制器(从左到右计数:0,1,2...)
    [tabBarController setSelectedIndex:1];
    tabBarController.delegate = self;
    [nav release];
    [myVC release];
    self.window.rootViewController = tabBarController;
           

运行效果如下:

【iOS开发】---- UITabBarController的使用详解
【iOS开发】---- UITabBarController的使用详解

隐藏tabBar:

- (void)makeTabBarHidden:(BOOL)hide
{
    if ( [self.tabBarController.view.subviews count] < 2 )
    {
        return;
    }
    UIView *contentView;
    
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
    {
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    }
    else
    {
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    }
    //    [UIView beginAnimations:@"TabbarHide" context:nil];
    if ( hide )
    {
        contentView.frame = self.tabBarController.view.bounds;        
    }
    else
    {
        contentView.frame = CGRectMake(self.tabBarController.view.bounds.origin.x,
                                       self.tabBarController.view.bounds.origin.y,
                                       self.tabBarController.view.bounds.size.width,
                                       self.tabBarController.view.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
    }
    self.tabBarController.tabBar.hidden = hide;
}
           

继续阅读