ios Tabbar 中间凸出简单有效的实现和hitTest:withEvent:方法

转载自: https://www.jianshu.com/p/b3fa05d2fc1a

 

效果.gif

 

效果如上,仅仅是要求中间的tabbar上移,并且上部分是有点击反应的。

创建UITabbarViewController

1、我们创建自己的YLeBaseViewController 集成 UITabBarController
并将其设置为整个window的rootViewController.

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    YLeBaseViewController *yLeBaseVC = [[YLeBaseViewController alloc] init];
    self.window.rootViewController = yLeBaseVC;
    [self.window makeKeyAndVisible];
    return YES;
}

2、我们设置tabbar的样式,以及每个tabbar按钮对应的页面

 

-(void)initWithTabbar{
    [UITabBar appearance].translucent = YES;//不透明
    [[UITabBar appearance] setBackgroundColor:[UIColor whiteColor]];
    
    YLeBaseNavigationController *navClub = (YLeBaseNavigationController *)[[YLeBaseNavigationController alloc] initWithRootViewController:[[UIViewController alloc] init]];
    YLeBaseNavigationController *navVideo = [(YLeBaseNavigationController *)[YLeBaseNavigationController alloc] initWithRootViewController:[[UIViewController alloc] init]];
    YLeBaseNavigationController *navHome = [(YLeBaseNavigationController *)[YLeBaseNavigationController alloc] initWithRootViewController:[[UIViewController alloc] init]];
    YLeBaseNavigationController *navLive = [(YLeBaseNavigationController *)[YLeBaseNavigationController alloc] initWithRootViewController:[[UIViewController alloc] init]];
    YLeBaseNavigationController *navMe = [(YLeBaseNavigationController *)[YLeBaseNavigationController alloc] initWithRootViewController:[[UIViewController alloc] init]];
    
    [self addChildVC:navClub title:@"" image:@"club_n" selectedImage:@"club"];//Club
    [self addChildVC:navVideo title:@"" image:@"video_n" selectedImage:@"video"];//Live
//只是占位
    [self addChildVC:navHome title:@"Home" image:@"" selectedImage:@""];
    [self addChildVC:navLive title:@"" image:@"live_n" selectedImage:@"live"];//Video
    [self addChildVC:navMe title:@"" image:@"me_n" selectedImage:@"me"];//Me
    
}

-(void)addChildVC:(UIViewController *)childVC title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage{
    childVC.tabBarItem.title = title;
    childVC.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 5, -5, -5);
    childVC.tabBarItem.image = [[UIImage imageNamed:image] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVC.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [childVC.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateNormal];
    [childVC.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor grayColor]} forState:UIControlStateSelected];
    [self addChildViewController:childVC];
}

我们此时有5个按钮,且中间一个是没有图片的。

接下来的重点:

1、中间的tabbar Button和其他的是不相同的。
我们写一个自己的tabbar 继承UITabBar,然后我们设置这个的UI

 

@interface YLeCenterTabbar : UITabBar

@property(nonatomic, strong) UIButton *centerBtn;

@end

 

-(instancetype)init{
    if (self = [super init]) {
        [self setViews];
    }
    return self;
}

-(void)setViews{
    self.centerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *normalImg = [UIImage imageNamed:@"home"];
    
    self.centerBtn.frame = CGRectMake(0, 0, normalImg.size.width, normalImg.size.height);
    [self.centerBtn setImage:normalImg forState:UIControlStateNormal];
    //btn center的位置位于tabbar的上边沿
    self.centerBtn.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - normalImg.size.width)/2.0, -normalImg.size.height/2.0, normalImg.size.width, normalImg.size.height);
    
    [self addSubview:self.centerBtn];
}

我们设置了图片,以及其中button的frame,之后我们通过KVC 的方式,用这个类型的实例变量替换系统的tabbar。接下来的重点是,我们点击这个替换之后按钮的时候是没有用的,于是我们需要在上面自定义按钮的时候添加:

 

//超出区域外点击无效
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
//tabbarVC 是否隐藏,隐藏了就不需要考虑点击了
    if (self.hidden) {
        return [super hitTest:point withEvent:event];
    }else{
        //将centerBtn上的点转化成父View上的点
        CGPoint touch = [self.centerBtn convertPoint:point fromView:self];
        //判断点击的点是否在按钮的区域内
        if (CGRectContainsPoint(self.centerBtn.bounds, touch)) {
            return _centerBtn;
        }else{
            return [super hitTest:point withEvent:event];
        }  
    }
}

此方法- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event;我们文章后面再说。

2、我们将自定义的tabbar的实例变量替换系统的

YLeBaseViewController.m

 

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.yLeCenterTab = [[YLeCenterTabbar alloc] init];
    self.yLeCenterTab.tintColor = [UIColor redColor];
    
    [self.yLeCenterTab.centerBtn addTarget:self action:@selector(centerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //利用kvc 将自己的tabbar赋值给系统的tabbar
    [self setValue:self.yLeCenterTab forKeyPath:@"tabBar"];
    self.selectItem = 0;
    self.delegate = self;
    
    [self initWithTabbar];
}

接下来我们需要实现UITabBarControllerDelegate,tabbar被选中的代理方法。

 

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    if(tabBarController.selectedIndex == 2){
        if (self.selectItem != 2) {
            [self rotationAnimation];
        }
    }else{
        [self.yLeCenterTab.centerBtn.layer removeAnimationForKey:@"shark"];
//        [self.yLeCenterTab.centerBtn.layer removeAllAnimations];
    }
    self.selectItem = tabBarController.selectedIndex;
}

然后是我们自己实现的button的click事件。

 

-(void)centerBtnClick:(id *)sender{
    NSLog(@"center btn click");
    self.selectedIndex = 2;
    if (self.selectItem != 2) {
        [self rotationAnimation];
    }
    self.selectItem = 2;
}

最后的抖动动画

 

//抖动
-(void)rotationAnimation{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"transform.rotation";
//    animation.repeatCount = 20;
    animation.repeatDuration = 60.0;
    animation.values = @[@(-M_PI_4 * 0.3),@(M_PI_4 * 0.3),@(-M_PI_4 * 0.3)];
    [self.yLeCenterTab.centerBtn.layer addAnimation:animation forKey:@"shark"];
}

github Demo
 

hitTest: withEvent: 调用过程

iOS系统事件的传递:

①.当手指触摸屏幕后会产生 '触摸事件', 然后将事件加入UIApplication的管理事件队列中
②.UIApplication会取出事件队列中 '最前面的事件' 分发下去,事先分发给应用程序的主窗口中 'keyWindow'
③.主窗口接收到事件后,分发给自己的子控件,寻找最适合的接收事件的控件
④.找到 '最适合' 接收的控件后,调用控件的touchesBegin/touchesMoved/touchesEnded方法
其中的第三步:
key window对象首先会使用hitTest:withEvent:方法寻找此次Touch操作初始点所在的视图(View),即需要将触摸事件传递给其处理的视图,称之为hit-test view。

window对象会发生一下操作
1、首先在view hierarchy的顶级view上调用hitTest:withEvent:,此方法会在视图层级结构中的每个视图上调用pointInside:withEvent:
2、[pointInside:withEvent:],查询触摸点是否在自己身上,当遍历子控件时,传入的坐标进行转换,将父视图上的坐标点转换成要传递子视图上的坐标点。
如果pointInside:withEvent:返回YES,则继续逐级调用,直到找到touch操作发生的位置,这个视图也就是hit-test view,如果返回NO,hit-test 方法返回nil。
总结:

hitTest的底层实现:当控件接收到触摸事件时,不管能不能处理事件,都会调用hit-test方法,方法的实现过程是:
1:先看自己是否能接受触摸事件
2:再看触摸点是否在自己身上
3:从后往前遍历所有子控件(从subviews数组的末尾向前遍历,直到有子视图返回非空对象或者全部子视图遍历完毕),拿到子控件后,再次重复1,2步骤,要把父控件上的坐标点转换为子控件坐标系下的点,再次执行hit-test方法
4:第一次有子视图返回非空对象,hit-test方法返回此对象,处理结束
5:假如所有子控件都返回非,则hit-test返回自身

控件不接收触摸事件的三种情况:
1> 不接收用户交互 userInteractionEnabled=NO
2> 隐藏 hidden = YES
3> 透明 alpha = 0.0 ~ 0.01
出现此三种情况的时候[hitTest:withEvent:]会忽略,不会去查找子控件。
假如子视图的部分超出父视图的bound区域,父视图没有裁剪(clipsToBounds=NO),超出父视图的部分也会显示,那么超出父视图之外区域的触摸操作不会被响应,因为父视图的pointInside:withEvent:返回NO,这样就不会遍历下面的子视图,此时如果需要相应就需要我们上面的操作。

 

//作用:去寻找最适合的View
//什么时候调用:当一个事件传递给当前View,就会调用.
//返回值:返回的是谁,谁就是最适合的View(就会调用最适合的View的touch方法)
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
   
    //1.判断自己能否接收事件
    if(self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) {
        return nil;
    }
    //2.判断当前点在不在当前View.
    if (![self pointInside:point withEvent:event]) {
        return nil;
    }
    //3.从后往前遍历自己的子控件.让子控件重复前两步操作,(把事件传递给,让子控件调用hitTest)
    int count = (int)self.subviews.count;
    for (int i = count - 1; i >= 0; i--) {
        //取出每一个子控件
        UIView *chileV =  self.subviews[i];
        //把当前的点转换成子控件坐标系上的点.
        CGPoint childP = [self convertPoint:point toView:chileV];
        UIView *fitView = [chileV hitTest:childP withEvent:event];
        //判断有没有找到最适合的View
        if(fitView){
            return fitView;
        }
    }
    
    //4.没有找到比它自己更适合的View.那么它自己就是最适合的View
    return self;
    
}

//作用:判断当前点在不在它调用View,(谁调用pointInside,这个View就是谁)
//什么时候调用:它是在hitTest方法当中调用的.
//注意:point点必须得要跟它方法调用者在同一个坐标系里面
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    NSLog(@"%s",__func__);
    return YES;
}



作者:后浪普拉斯
链接:https://www.jianshu.com/p/b3fa05d2fc1a
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值