自定义一个形状不规则的TabBar,改变响应区域

96
SamChenzx
2017.01.07 22:18* 字数 950

在使用TabBarController的过程中,经常需要让TabBar的item点击事件能加上动画,或者item需要用较大的图片,超出了TabBar的高度与最大的图片像素限制。这种情况下,在TabBarController中,使用默认的TabBar比较难实现,超出TabBar高度的区域不会响应点击事件,色彩过于丰富的图片甚至无法正常显示。自定义TabBar如下两个APP:


飞猪首页TabBar
inke TabBar.gif

对于这样的TabBar,我们往往需要自定义。本文仿映客iOS客户端的自定义TabBar思路是先用UIView来绘制所需要的样式,用Button代替其上的item,将绘制好的View作为subView添加到self上(self是一个TabBar对象)。定义delegate来处理对应按钮的点击事件。为了解决中间按钮部分覆盖了左右两个Button,并且高出底下View高度,导致形状不规则使点击事件无法正确响应的问题,重写了-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event方法,最后,用KVC的方式替换了TabBarController中的默认TabBar。

首先,创建一个基于UITabBar的子类SamTabBar。为什么基于UITabBar而不是UIView?因为TabBarController和NavigationController结合时,当我们想push到一个childVC时,在其中调用[self.navigationController pushViewController:childVC animated:YES];,可以使用系统自带的属性childVC.hidesBottomBarWhenPushed = YES;让TabBar在push时自动隐藏,而不用自己添加一些动画代码来完成这一效果。

上自定义SamTabBar.h代码:

//
//  SamTabBar.h
//
#import <UIKit/UIKit.h>
// If you need to add other buttons on the tabbar, you need to add corresponding enum types first.
typedef NS_ENUM(NSInteger, SamItemType) {
    
    SamItemTypeLaunch = 10,// Launch live
    SamItemTypeLive = 100, // show live
    SamItemTypeMe,         // show me
    // Other types
};

@class SamTabBar;

@protocol SamTabBarDelegate <NSObject>

-(void)tabBar:(SamTabBar *)tabBar clickButton:(SamItemType) index;

@end

@interface SamTabBar : UITabBar
@property(nonatomic, assign) id<SamTabBarDelegate> delegate;
@end

在SamTabBar.m中,重写hitTest:方法主要解决中间启动直播按钮引起的不规则问题。

//
//  SamTabBar.m
//
#import "SamTabBar.h"

@interface SamTabBar()
@property(nonatomic, strong) UIButton *cameraButton;
@end

@implementation SamTabBar

// basic implementation...

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.translucent = NO;
        // add items
        for (NSInteger i = 0; i<self.datalist.count; i++) {
            UIButton *item = [UIButton buttonWithType:UIButtonTypeCustom];
            item.adjustsImageWhenHighlighted = NO;
            [item setImage:[UIImage imageNamed:self.datalist[i]] forState:UIControlStateNormal];
            [item setImage:[UIImage imageNamed:[self.datalist[i] stringByAppendingString:@"_p"]] forState:UIControlStateSelected];
            if (i == 0) {
                item.selected = YES;
                self.lastItem = item;
            }
            item.tag = SamItemTypeLive + i;
            [item addTarget:self action:@selector(clickItem:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:item];
        }
    }
    [self addSubview:self.cameraButton];
    return self;
}
// 调整子视图的布局
-(void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat width = self.frame.size.width/self.datalist.count;
    
    for (NSInteger i = 0; i<[self subviews].count; i++) {
        UIView *btn = [self subviews][i];
        if ([btn isKindOfClass:[UIButton class]]) {
            btn.frame = CGRectMake((btn.tag - SamItemTypeLive)*width, 0, width, self.frame.size.height);
        }
    }
    [self.cameraButton sizeToFit];
    self.cameraButton.center = CGPointMake(self.frame.size.width/2, 10);
}

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
//  to make sure the tabBar won't respond any touch event when hidden
    if (self.isHidden) {
        return nil;
    }
    UIView *view = nil;
    for (UIView *subView in self.subviews) {
        CGPoint testPoint = [subView convertPoint:point fromView:self];
        if (CGRectContainsPoint(subView.bounds, testPoint)) {
            if (CGRectContainsRect(subView.bounds, self.cameraButton.bounds)) {
                view = subView;
                return view;
            } else if ([subView isKindOfClass:[UIButton class]]) {
                view = subView;
            }
        }
    }
    if (view == nil) {
        view = [super hitTest:point withEvent:event];
    }
    return view;
}

-(void)clickItem:(UIButton *)button
{
    if ([self.delegate respondsToSelector:@selector(tabBar:clickButton:)]) {
        [self.delegate tabBar:self clickButton:button.tag];
    }
    //!self.block?:self.block(self,button.tag);
    if (self.block) {
        self.block(self,button.tag);
    }
    if (button.tag == SamItemTypeLaunch) {
        return;
    }
    
    self.lastItem.selected = NO;
    button.selected = YES;
    self.lastItem = button;
    [UIView animateWithDuration:0.2
                     animations:^{
                         button.transform = CGAffineTransformMakeScale(1.2, 1.2);
                     } completion:^(BOOL finished) {
                         [UIView animateWithDuration:0.2
                                          animations:^{
                                              button.transform = CGAffineTransformIdentity;
                                          }];
                     }];
}

clickItem:为tabbar上button对应的点击事件,里面通过delegate传递消息。-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event方法会在一次事件到来后,从根视图到子视图遍历,找出这个点所在的离手指最近的子视图来响应事件。但是,默认的hitTest:并不能解决落在父视图bounds外的子视图的点击事件,也就是不能解决不规则区域的点击事件,因此,我们需要重载该方法。在本文中,主要需要解决的是中间钮引的不规则问题,所以先用CGPoint testPoint = [subView convertPoint:point fromView:self];将点击坐标从屏幕坐标系,转换到当前遍历到的subView自身坐标系中,再去判断这个subView是否包含了中间的不规则buttonCGRectContainsRect(subView.bounds, self.cameraButton.bounds)。如果包含,则当前点击的就是self.cameraButton,直接返回,终止遍历;否则,点击的可能是左右两个TabBar上的自定义Button,需要再去判断subView是否为UIButton对象;如果遍历完都没有找到对应的subView,则调用默认hitTest:方法。这样一个不规则的TabBar就定义好了。在hitTest:入口加上

        return nil;
    }```
以确保当TabBar被隐藏时,不会响应任何点击事件

在TabBarViewController.m中使用自定义的TabBar:

//
// SamTabBarViewController.m
//

import "SamTabBarViewController.h"

@interface SamTabBarViewController () <SamTabBarDelegate>

@property(nonatomic, strong) SamTabBar* samTabBar;

@end

@implementation SamTabBarViewController

-(SamTabBar *)samTabBar
{
if (!_samTabBar) {
_samTabBar = [[SamTabBar alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 50, [UIScreen mainScreen].bounds.size.width, 50)];
_samTabBar.delegate = self;
}
return _samTabBar;
}

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // add controller
    [self configViewControllers];
    // add tabbar
    [[UITabBar appearance] setShadowImage:[UIImage new]];
    [self setValue:self.samTabBar forKey:@"tabBar"];
    }

-(void)configViewControllers
{
//准备子控制器
NSMutableArray *array = [NSMutableArray arrayWithArray:@[@"AViewController",@"BViewController"]];
for (NSInteger i = 0; i<array.count; i++) {
NSString *vcName = array[i];
UIViewController *vc = [[NSClassFromString(vcName) alloc]init];
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
[array replaceObjectAtIndex:i withObject:nav];
}
self.viewControllers = array;
}

-(void)tabBar:(SamTabBar *)tabBar clickButton:(SamItemType)index
{
if (index != SamItemTypeLaunch) {
self.selectedIndex = index - SamItemTypeLive;
} else if(index == SamItemTypeLaunch) {
[self.launchOptionView showUp];
}
}

在viewDidLoad方法中,实现```-(void)tabBar:(SamTabBar *)tabBar clickButton:(SamItemType)index```方法,用于正确显示需要显示的viewController。使用``` [self setValue:self.samTabBar forKey:@"tabBar"];```方法,就可以用自定义TabBar替换默认TabBar。稍微完整的Demo在[这里。](https://github.com/SamChenzx/inke_trick)
iOS开发
Web note ad 1