TabBarController 自定义

一. iOS中的TabBarController确实已经很强大了,但是有时候不能满足我们的需求,因此需要自定义TabBar

二.自定义TabBar的总体过程
原则:尽量利用系统自带TabBar,只改需要改的地方。

  1. 把自带的 TabBar 条给隐藏
  2. 创建一个 view, 上面放几个按钮 , 设定按钮的点击事件,并设置 selectIndex。
    3.关联各个子viewController,覆盖相关事件。(用 tabbar 的 selectedIndex 属性 . 设置这个属性就行了)
  3. 取消系统的高亮 :
    可以自定义一个按钮 . 重写里面的 setHighhighted 方法 , 什么也不做即可
  4. 关于几个按钮只选中一个的方法 :
    • 设置一个属性 , 记录上一个选中的按钮 .
    • 点击当前按钮时 , 把上一个按钮设置为未选中 , 并把当前按钮设置为选中 , 最后把当前按钮赋值给上一个按钮 .
    三.代码如下:
    LUTabBarController.h
#import 

@interface LUTabBarController : UITabBarController

@end

LUTabBarController.m

#import "LUTabBarController.h"
#import "LUTabBarButton.h"

#import 
#import 


@interface LUTabBarController ()
/**
 *  设置之前选中的按钮
 */
@property (nonatomic, weak) UIButton *selectedBtn;
@end

@implementation LUTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];

    //删除现有的tabBar
    CGRect rect = self.tabBar.frame;

    self.tabBar.hidden = YES;//TabBarController自带的下部的条
    //测试添加自己的视图
    UIView *myView = [[UIView alloc] init];
    myView.frame = rect;
    myView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:myView];
    [self.view bringSubviewToFront:myView];
    for (int i = 0; i < 3; i++) {
        //UIButton *btn = [[UIButton alloc] init];
        LUTabBarButton *btn = [[LUTabBarButton alloc] init];
        
        NSString *imageName = [NSString stringWithFormat:@"lutabBar%d", i + 1];
        NSString *imageNameSel = [NSString stringWithFormat:@"lutabBar%dSel", i + 1];
        
        [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:imageNameSel] forState:UIControlStateSelected];
        
        CGFloat x = i * myView.frame.size.width / 3;
        btn.frame = CGRectMake(x, 0, myView.frame.size.width / 3, myView.frame.size.height);
        
        [myView addSubview:btn];
        btn.tag = i;//设置按钮的标记, 方便来索引当前的按钮,并跳转到相应的视图
        
        //带参数的监听方法记得加"冒号"
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        //设置刚进入时,第一个按钮为选中状态
        if (0 == i) {
            btn.selected = YES;
            self.selectedBtn = btn;  //设置该按钮为选中的按钮
        }
    }
}



/**
 *  自定义TabBar的按钮点击事件
 */
- (void)clickBtn:(UIButton *)button {
    //1.先将之前选中的按钮设置为未选中
    self.selectedBtn.selected = NO;
    //2.再将当前按钮设置为选中
    button.selected = YES;
    //3.最后把当前按钮赋值为之前选中的按钮
    self.selectedBtn = button;

    //4.跳转到相应的视图控制器. (通过selectIndex参数来设置选中了那个控制器)
    self.selectedIndex = button.tag;
}

@end

LUTabBarButton.h

#import 

@interface LUTabBarButton : UIButton

@end

LUTabBarButton.m

#import "LUTabBarButton.h"
@implementation LUTabBarButton
/**什么也不做就可以取消系统按钮的高亮状态*/
- (void)setHighlighted:(BOOL)highlighted{
//    [super setHighlighted:highlighted];
}

@end

你可能感兴趣的:(TabBarController 自定义)