当程序需要分成几个相对独立的部分时,可以考虑使用 UITabBarController
组合多个视图控制器,UITabBarController
会在底部提供一个 UITabBar
,用户点击不同的标签项,整个应用可以呈现完全不同的部分。
UITabBar
控件代表一个标签条,它是 UITabBarItem
的容器,可以用于组合多个 UITabBarItem
对象,一个 UITabBarItem
对象就代表一个标签项。
> UITabBar的使用:
UITabBar控件可以设置这两个属性:Tint(对应于UITabBar的tintColor属性设置背景色),Image Tint(对应于UITabBar的selectedImageTintColor属性,用于设置UITabBar选中项上图标的高亮颜色)
UITabBar访问UITabBarItem标签项,属性:items,selectedItem,setItems:animated:
创建UITabBarItem:initWithTabBarSystemItem:tag:/initWithTitle:image:tag:/badgeValue创建了tag标签以便识别
使用步骤:
1.创建一个UITabBar对象。
2.创建多个UITabBarItem对象,并将这些UITabBarItem设置给UITabBar对象
3.为UITabBar对象设置一个UITabBarDelegate协议的对象。当用户选中某一个标签项时,将会激发UITabBarDelegate协议中的tabBar:didSelectItem:方法。
> UITabBarController控制器的代码使用:
1. 创建继承自UITabBarViewController的控制器
2. 设置这个控制器为root控制器
3. 在tabBarController控制器中设置各个标签页控制器(具体设置如下代码)
FirstViewController *first = [[FirstViewController alloc]init];
UINavigationController *nav1 = [[UINavigationController alloc]initWithRootViewController:first];
nav1.tabBarItem.title = @"First";
///
SecondViewController *second = [[SecondViewController alloc]init];
UINavigationController *nav2 = [[UINavigationController alloc]initWithRootViewController:second];
nav2.tabBarItem.title = @"Second";
///
self.viewControllers = @[nav1,nav2];
> UITabBar和UITabBarController
把一个视图控制器作为容器视图控制器,在这个容器视图控制器上添加多个其他视图控制器,并把其他控制器的视图添加上来
使用场景:当我们某个视图控制器要使用多个子界面,并且多个子界面的处理事务的逻辑比较复杂,我们就可以通过这种方式将不同的逻辑处理拆分开,在各自的视图控制器中处理自己的逻辑,而不是所有逻辑都在当前视图控制器中处理。
TableViewController *tableViewController = [[TableViewController alloc] init];
[self addChildViewController:tableViewController]; // self在这里就是容器视图控制器
[self.view addSubView:tableViewController.tableView];
> 设置自定义UITabBarController
//选中item背景颜色
// CGSize indicatorImageSize = CGSizeMake(self.tabBar.bounds.size.width/self.tabBar.items.count, self.tabBar.bounds.size.height);
// self.tabBar.selectionIndicatorImage = [self drawTabBarItemBackgroundImageWithSize:indicatorImageSize];
//
-(UIImage *)drawTabBarItemBackgroundImageWithSize:(CGSize)size
{
//准备绘图环境
UIGraphicsBeginImageContext(size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(ctx, 124.0/255, 124.0/255, 151.0/255, 1.0);
CGContextFillRect(ctx, CGRectMake(0, 0, size.width, size.height));
//
//获取该绘图中的图片
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
//结束绘图
UIGraphicsEndImageContext();
return img;
}
在使用时必须加上这一句图片才能正常显示!!!
for (UITabBarItem *item in self.tabBar.items) {
item.selectedImage = [item.selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//
item.image = [item.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
网友评论