(转)自定义UITabBar

push页面时,可调用hidesBottomBarWhenPushed进行隐藏。

第一步,我们需要一些图片:

各个选项的图标和tabbar的背景图片,最后还要一个透明的1x1像素的图片。

第二步,新建一个工程,在工程内建一个继承于UITabBarController的类。

第三步,首先写一个方法,返回一个UINavigationController

[objc] view plaincopy
 
  1. -(UINavigationController*) viewControllerWithTitle:(NSString*) title image:(UIImage*)image  
  2. {  
  3.     UIViewController* viewController = [[UIViewController alloc] init];  
  4.     viewController.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:image tag:0];  
  5.     viewController.title = title;  
  6.     UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:viewController];  
  7.     return nav;  
  8. }  


然后在viewDidLoad里面创建TabbarController的viewControllers

[objc] view plaincopy
 
  1. self.viewControllers = [NSArray arrayWithObjects:  
  2.                            [self viewControllerWithTitle:@"1" image:IMG(@"1")],  
  3.                            [self viewControllerWithTitle:@"2" image:IMG(@"2")],  
  4.                            [self viewControllerWithTitle:nil image:nil],  
  5.                            [self viewControllerWithTitle:@"3" image:IMG(@"3")],  
  6.                            [self viewControllerWithTitle:@"4" image:IMG(@"4")], nil nil];  


看到没有,比较猥琐的就是第三个ViewController什么都没设置。

因为我们要在那个位置放一个自己的按钮,继续在viewDidLoad写:

[objc] view plaincopy
 
  1. UIButton* button = [[UIButton alloc]initWithFrame:CGRectMake(0.0, 0.0, 65, 65)];  
  2. button.center = CGPointMake(160, 20);  
  3. [button setBackgroundImage:IMG(@"add") forState:UIControlStateNormal];  
  4. [button addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];  
  5. [self.tabBar addSubview:button];  

然后设置背景图片:

[objc] view plaincopy
 
  1. [self.tabBar setBackgroundImage:IMG(@"tabbarbg")];  

运行之后是这样的:



会发现按钮上面有一条横线,然后再设置这个阴影运行后就没有人发现你猥琐的行径。

[objc] view plaincopy
 
  1. [self.tabBar setShadowImage:IMG(@"transparent")];  

最后效果图(iOS7和iOS6):


这样做的好处:

在ViewController里push页面的时候可调用hidesBottomBarWhenPushed的属性进行隐藏。

原文地址:https://www.cnblogs.com/code-changeworld/p/4654015.html