1. 程式人生 > >iOS自定義tabbar(沒有tabbar上的黑線)

iOS自定義tabbar(沒有tabbar上的黑線)

自定義tabbar相信在很多專案中都要用到。有的時候 還需要那種 不規則的tabbar,例如中間高兩邊底,例如需要新增tabbar的背景圖片等等。這裡 我要介紹一種 自定義tabbar的方法 ,這種方法可以呼叫系統的 hidesBottomBarWhenPushed 方法,很方便的隱藏tabbar。

話不多說開始正文。

第一步:
首先建立 tabbarViewController 繼承自 UITabBarController

第二步:
裝載檢視控制器 上程式碼

//裝載檢視
-(void)addViewController
{
    UIViewController
* vc1 = [[UIViewController alloc]init]; vc1.view.backgroundColor = [UIColor redColor]; vc1.title = @"收益權"; UINavigationController * nvc1 = [[UINavigationController alloc]initWithRootViewController:vc1]; ViewController * vc2 = [[ViewController alloc]init]; UINavigationController
* nvc2 = [[UINavigationController alloc]initWithRootViewController:vc2]; vc2.view.backgroundColor = [UIColor blueColor]; vc2.title = @"個人中心"; ViewController * vc3 = [[ViewController alloc]init]; UINavigationController * nvc3 = [[UINavigationController alloc]initWithRootViewController:vc3]; vc3.view
.backgroundColor = [UIColor lightGrayColor]; vc3.title = @"論壇"; self.viewControllers = @[nvc1,nvc2,nvc3]; }

第三部 自定義tabbar

-(void)customTab
{
    //這裡是去掉 系統tabbar上黑線的方法
    self.tabBar.backgroundImage = [[UIImage alloc]init];
    self.tabBar.shadowImage = [[UIImage alloc]init];

    UIImageView * image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 49)];
    image.backgroundColor = [UIColor grayColor];
    image.userInteractionEnabled = YES;
    [self.tabBar addSubview:image];

    for (int i = 0;  i<3 ; i++) {
        UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/3 *i +10, 5, ScreenWidth/4, 30)];
        if(i == 1)
        {
            btn.frame = CGRectMake(ScreenWidth/3 *i, -11, ScreenWidth/3, 60);
        }
        switch (i) {
            case 0:
                btn.backgroundColor = [UIColor redColor];
                break;
            case 1:
                btn.backgroundColor = [UIColor yellowColor];
                break;
            case 2:
                btn.backgroundColor = [UIColor blueColor];
                break;
            default:
                break;
        }
        btn.tag = i ;
        [btn addTarget:self action:@selector(toudown:) forControlEvents:UIControlEventTouchDown];
        [image addSubview:btn];
    }
}

不要玩了 btn的點選事件方法

-(void)toudown:(UIButton *)btn
{
    self.selectedIndex = btn.tag;
}

可以看到 自定義的tabbar 上
背景圖片是一張 UIImageView ,你想要什麼背景 直接找 UI 美眉要就好了。
tabbar上的 三個按鈕 你想要什麼樣式的都行,UI切圖就好了。

第四步: 完成

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addViewController];
    [self customTab];
}

在viewDidLoad裡 條用這連個方法就好了。

最後附上 github 原始碼
https://github.com/lwq718691587/custom-tabbar