关于UITabBar各部分自定义的代码片段
2012-01-03 14:26 张智清 阅读(8728) 评论(0) 编辑 收藏 举报一、自定义TabBar选项卡背景
默认UITabBarController的TabBar背景是黑色的,如何自定义成背景图片呢?
UITabBarController *tabBarController = [[UITabBarController alloc] init];
// 获取选项卡控制器视图的所有子视图,保存到一数组中
NSArray *array = [tabBarController.view subviews];
// 索引值为1的应该就是TabBar
UITabBar *tabBar = [array objectAtIndex:1];
// UIImage *image = [UIImage imageNamed:@"tabbarbg.png"];
UIImage *image = [UIImage imageWithContentsOfFile:sourcePath];
tabBar.layer.contents = (id)image.CGImage;
或者:
tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers: view_manager];
UIImageView *tab_imgv = [UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabbar_bg.png"]];
tab_imgv.frame = CGRectMake(0,0,320,49);
tab_imgv.contentMode = UIViewContentModeScaleToFill;
// 为什么atIndex是1,看SDK
[[tabBarController tabBar] insertSubview:tab_imgv atIndex:1];
[tab_imgv release];
[view_manager release];
或者:
UITabBarController *tabBarController = [[UITabBarController alloc] init];
// 初始化一矩形视图框架
CGRect frame = CGRectMake(0,0,320,49);
UIView *v = [[UIView alloc] initWithFrame:frame];
// 以图片为平铺的颜色模板,初始化颜色
UIImage *img = [UIImage imageNamed:@"tabbarbg.png"];
UIColor *color = [[UIColor alloc] initWithPatternImage:img];
// 设置视图背景色
v.backgroundColor = color;
// 将视图插入到选项卡栏底层
[tabBarController.tabBar insertSubview:v atIndex:0];
tabBarController.tabBar.opaque = YES;
[color release];
[v release];
或者:在UITabBarController子类中重写init方法来初始化
- (id)init {
if(self=[super init]){
//方法一
UIImageView *imgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabbarbg.png"]];
imgv.frame = CGRectMake(0,0,self.tabBar.frame.size.width,self.tabBar.frame.size.height);
imgv.contentMode = UIViewContentModeScaleToFill;
// imgv.frame = CGRectOffset(imgv.frame,0,1);
[[self tabBar] insertSubview:imgv atIndex:0];
[imgv release];
// 方法二
CGRect frame = CGRectMake(0,0,self.view.bounds.size.width,49);
UIView *view = [[UIView alloc] initWithFrame:frame];
UIImage *tabImage = [UIImage imageNamed:@"tabbg.png"];
UIColor *color = [[UIColor alloc] initWithPatternImage:tabImage];
[view setBackgroundColor:color];
[color release];
[[self tabBar] insertSubview:view atIndex:0];
[view release];
}
}
当然在iOS5开始就最方便了,在iOS5中提供了一个API来设置UITabBar的背景图片,以及表示选中的图片。
UIImage *tabBackground = [[UIImage imageNamed:@"tab_bg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
[[UITabBar appearance] setBackgroundImage:tabBackground];
[[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageNamed:@"tab_select_indicator.png"]];
二、隐藏TabBar
- 隐藏系统TabBar,但仍占位置。
- (void)hideExsitingTabBar {
for(UIView *view in self.view.subviews)
{
if([view isKindOfClass:[UITabBar class]])
{
view.hidden = YES;
break;
}
}
} - 彻底隐藏TabBar:如从一个有TabBar控制器的视图转入另外一新视图,且没有上一视图的TabBar。
nextViewController.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:nextViewController animated:NO];