自定义TabBarController

一、前言

IOS中的TabBarController确实已经很强大了,但有时也不能完全满足全部的需求(如增加自定义的功能、增加自己想要的效果),因此有时需要自定义TabBar。

二、自定义TabBar的总体实现步骤

1.先把系统自带的TabBar条取消掉。

2.自定义一个UIView,上面放几个按钮,设定按钮的点击事件,并设置selectIndex。

3.关联各个子viewController,覆盖相关事件。

三、实现时需要注意的细节

1.删除系统自带的初始化tabbar控件。

2.让自己创建的按钮关联到相应的viewController。(利用tabbar的selectedIndex属性实现)

3.自定义按钮之间的切换,需要设置默认选中的按钮以及只能选中一个按钮(设置一个属性,记录被选中的按钮。点击当前按钮时,把上一个按钮设置为未选中,并把当前按钮设置为选中,最后把当前按钮赋值给上一个按钮),如下面代码所示:

//监听按钮点击

- (void)buttonClick:(JTabbarButton *)button
{
    //1.通知代理
    //切换视图控制器
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectedButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectedButtonFrom:self.selectedButton.tag to:button.tag];
    }
    //2.按钮的切换
    //2.1 先将之前选中的按钮设置为未选中
    self.selectedButton.selected = NO;
    //2.2 再将当前按钮设置为选中
    button.selected = YES;
    //2.3 最后把当前按钮赋值为之前选中的按钮
    self.selectedButton = button;
}


四、代码实现过程

TabbarButton代码实现

1.自定义的TabbarButton,头文件JTabbarButton.h

#import <UIKit/UIKit.h>

@interface JTabbarButton : UIButton
@property (nonatomic,strong) UITabBarItem *item;
@end
2.实现部分,实现代码JTabbarButton.m

2.1 设置TabbarButton初始化属性

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        //设置TabbarButton的属性
        self.imageView.contentMode = UIViewContentModeCenter;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:11];
        
        [self setTitleColor: WBTarBarButtontitleColor forState:UIControlStateNormal];
        [self setTitleColor: WBTarBarButtontitleSelected forState:UIControlStateSelected];
        if (!IOS7) {
            [self setBackgroundImage:[UIImage imageNamed:@"tabbar_slider"] forState:UIControlStateSelected];
        }

    }
    return self;
}

2.2 重写setHighlighted方法,取消系统的高亮以及指定按钮图片、文字标题边界。

/**
 *  重写setHighlighted方法,取消系统的高亮。
 *
 *  @param highlighted
 */
- (void)setHighlighted:(BOOL)highlighted
{
    
}

/**
 *  指定按钮图片边界
 *
 *  @param contentRect <#contentRect description#>
 *
 *  @return <#return value description#>
 */
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat imageW = contentRect.size.width;
    CGFloat imageH = contentRect.size.height * WBTabBarButtonratio;
    return CGRectMake(0, 0, imageW, imageH);
}

/**
 *  指定文字标题边界
 *
 *  @param contentRect <#contentRect description#>
 *
 *  @return <#return value description#>
 */
-(CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGFloat titleY = contentRect.size.height * WBTabBarButtonratio;;
    CGFloat titleW = contentRect.size.width;
    CGFloat titleH = contentRect.size.height * (1.0-WBTabBarButtonratio);
    return CGRectMake(0, titleY, titleW, titleH);
}
2.3 利用kvo监听属性的变化并赋值

- (void)setItem:(UITabBarItem *)item
{
    _item = item;
    
    // KVO
    //[item addObserver:self forKeyPath:@"badgeValue" options:0 context:nil];
    [item addObserver:self forKeyPath:@"image" options:0 context:nil];
    [item addObserver:self forKeyPath:@"selectedImage" options:0 context:nil];
    [item addObserver:self forKeyPath:@"title" options:0 context:nil];
    
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
    
    
}

/**
 *  移除KVO监听
 */
-(void)dealloc
{
    //[self.item removeObserver:self forKeyPath:@"badgeValue"];
    [self.item removeObserver:self forKeyPath:@"image"];
    [self.item removeObserver:self forKeyPath:@"selectedImage"];
    [self.item removeObserver:self forKeyPath:@"title"];
}


/**
 *  监听某个对象的属性改变了,就会调用
 *
 *  @param keyPath 属性名
 *  @param object  哪个对象的属性被改变
 *  @param change  属性发生的改变
 *  @param context <#context description#>
 */

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    //设置文字
    [self setTitle:self.item.title forState:UIControlStateNormal];
    [self setTitle:self.item.title forState:UIControlStateSelected];
    //设置图片
    [self setImage:self.item.image forState:UIControlStateNormal];
    [self setImage:self.item.selectedImage forState:UIControlStateSelected];
    
}

JTabbar代码实现

3.由 TabbarButton组成的JTabbar,头文件JTarbar.h

#import <UIKit/UIKit.h>

@class JTabbar;

@protocol JTabBarDelegate <NSObject>
//可选的代理方法
@optional
//监听按钮的点击
-(void)tabBar:(JTabbar *)tabBar didSelectedButtonFrom:(int)from to:(int)to;
-(void)tabBarDidClickPlusButton:(JTabbar *)tabBar;
@end

@interface JTabbar : UIView
-(void)addTabBarButtonWithItem:(UITabBarItem *)item;
@property (nonatomic,weak) id<JTabBarDelegate> delegate;

@end
4. 实现部分,实现代码JTabbar.m

4.1 设置可变组数

@property (nonatomic,strong) NSMutableArray *TabbarButtons;
可变数组用于保存添加的 TabbarButton。为可变数组添加懒加载,提高效率

//懒加载
-(NSMutableArray *)TabbarButtons
{
    if (_TabbarButtons == nil) {
        _TabbarButtons = [NSMutableArray array];
    }
    return  _TabbarButtons;
}

4.2 在初始化阶段添加“+”按钮

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        if (!IOS7) {
            self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tabbar_background"]];
        }
        
        UIButton *plusButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [plusButton setBackgroundImage:[UIImage imageWithName:@"tabbar_compose_button"] forState:UIControlStateNormal];
        [plusButton setBackgroundImage:[UIImage imageWithName:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
        
        [plusButton setImage:[UIImage imageWithName:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
        [plusButton setImage:[UIImage imageWithName:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];
        [plusButton addTarget:self action:@selector(ClickPlusButton) forControlEvents:UIControlEventTouchDown];
        
        plusButton.bounds = CGRectMake(0, 0, plusButton.currentBackgroundImage.size.width, plusButton.currentBackgroundImage.size.height);
        [self addSubview:plusButton];
        self.plusButton = plusButton;

        
    }
    return self;
}
4.3 为 “+”按钮添加点击事件

#pragma mark - 加号按钮点击事件处理器
-(void)ClickPlusButton
{
    //通知代理
    if ([self.delegate respondsToSelector:@selector(tabBarDidClickPlusButton:)]) {
        [self.delegate tabBarDidClickPlusButton:self];
    }
}
4.4 为 TabbarButton设置数据、添加按钮点击事件以及默认选中第0个按钮

- (void)addTabBarButtonWithItem:(UITabBarItem *)item
{
    //1.创建按钮
    JTabbarButton *button = [[JTabbarButton alloc]init];
    [self addSubview:button];
    [self.TabbarButtons addObject:button];
    
    //2.设置数据
    button.item = item;
    
    //3.监听按钮点击
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    
    //4.默认选中第0个按钮
    if (self.TabbarButtons.count == 1) {
        [self buttonClick:button];
    }
    
}
4.5 监听按钮的点击事件以及按钮的切换

//监听按钮点击

- (void)buttonClick:(JTabbarButton *)button
{
    //1.通知代理
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectedButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectedButtonFrom:self.selectedButton.tag to:button.tag];
    }
    //2.按钮的切换
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
}
4.6 子视图按钮的布局

- (void)layoutSubviews
{
    CGFloat h = self.frame.size.height;
    CGFloat w = self.frame.size.width;
    self.plusButton.center = CGPointMake(w*0.5, h*0.5);
    
    CGFloat buttonH = self.frame.size.height;
    CGFloat buttonW = self.frame.size.width / self.subviews.count;
    
    CGFloat buttonY = 0;
    for (int index =0; index<self.TabbarButtons.count; index++) {
        //1.取出按钮
        JTabbarButton *button = self.TabbarButtons[index];
        
        //2.设置按钮的frame
        CGFloat buttonX = index * buttonW;
        if (index > 1) {
            buttonX += buttonW;
        }
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        //3.绑定tag
        button.tag = index;
    }
}
5.自定义TabBarController的JTabBarViewController实现

5.1 初始化tabbar以及代理的设置

//初始化tabbar
-(void)setupTabbar
{
    JTabbar *jtabbar = [[JTabbar alloc] init];
    jtabbar.frame = self.tabBar.bounds;
    
    jtabbar.delegate = self;
    [self.tabBar addSubview:jtabbar];
    self.jtabbar = jtabbar;
}
5.2 初始化所有子控件

//初始化所有子控制器

-(void)setUpAllChildViewController
{
    //首页
    JhomepageTableViewController *home = [[JhomepageTableViewController alloc] init];
    //home.tabBarItem.badgeValue = @"10";
    [self setUpChildViewControlller:home title:@"首页" imageName:@"tabbar_home" selectedImageName:@"tabbar_home_selected"];
 
    JmessageTableViewController *message = [[JmessageTableViewController alloc] init];
    //message.tabBarItem.badgeValue = @"890";
    [self setUpChildViewControlller:message title:@"消息" imageName:@"tabbar_message_center" selectedImageName:@"tabbar_message_center_selected"];
    
    JsquareTableViewController *square = [[JsquareTableViewController alloc] init];
    //square.tabBarItem.badgeValue = @"8";
    [self setUpChildViewControlller:square title:@"广场" imageName:@"tabbar_discover" selectedImageName:@"tabbar_discover_selected"];
    JuserTableViewController *user = [[JuserTableViewController alloc] init];
    //user.tabBarItem.badgeValue = @"6";
    [self setUpChildViewControlller:user title:@"我" imageName:@"tabbar_profile" selectedImageName:@"tabbar_profile_selected"];
    
}
5.3 代理方法的实现

#pragma mark --代理方法
/***
 监听Tabbar按钮的改变
 
 */
-(void)tabBar:(JTabbar *)tabBar didSelectedButtonFrom:(int)from to:(int)to
{
    //    NSLog(@"---%d---%d",from,to);
    self.selectedIndex = to;
}

-(void)tabBarDidClickPlusButton:(JTabbar *)tabBar
{
    JComposeViewController *compose = [[JComposeViewController alloc] init];
    
    WBNavigationViewController *nav = [[WBNavigationViewController alloc] initWithRootViewController:compose];
    [self presentViewController:nav animated:YES completion:nil];
}

效果图如下图所示:


源代码下载地址:http://download.csdn.net/detail/jasonjwl/9313899

GitHub地址:https://github.com/jingwanli6666/TabbarController


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值