美文网首页
UITabBar圆形凸起按钮边缘响应点击

UITabBar圆形凸起按钮边缘响应点击

作者: 倪大头 | 来源:发表于2018-03-30 01:33 被阅读19次

    自定义一个UITabbar:

    MyUITabBar.h

    圆形按钮点击事件需要写一个delegate

    #import <UIKit/UIKit.h>
    
    @protocol CenterBtnDelegate <NSObject>
    
    - (void)DidClickCenterBtn;
    
    @end
    
    @interface MyUITabBar : UITabBar
    
    @property (nonatomic, weak)id <CenterBtnDelegate>centerBtnDelegate;
    
    @end
    

    MyUITabBar.m

    centerBtn就是要创建的“大按钮”,点击方法用了RAC,跟本功能无关
    重点是这个方法

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
    

    切换当前触摸点的坐标系,使“大按钮”凸起部分可以响应点击事件

    #import "MyUITabBar.h"
    #import <ReactiveCocoa/ReactiveCocoa.h>
    
    @implementation MyUITabBar
    {
        UIButton *centerBtn;
    }
    
    - (instancetype)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            //中间的圆按钮
            centerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            centerBtn.frame = CGRectMake(UI_SCREEN_WIDTH/2-kScaleX*30, -(kScaleY*60-49), kScaleX*60, kScaleY*60);
            [centerBtn setImage:[UIImage imageNamed:@"圆按钮"] forState:UIControlStateNormal];
            centerBtn.layer.cornerRadius = centerBtn.frame.size.height/2;
            centerBtn.clipsToBounds = YES;
            [self addSubview:centerBtn];
            
            [[centerBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
                if ([self.centerBtnDelegate respondsToSelector:@selector(DidClickCenterBtn)]) {
                    [self.centerBtnDelegate DidClickCenterBtn];
                }
            }];
        }
        return self;
    }
    
    //重写此方法,让按钮凸起部分也响应点击事件
    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
        if (self.isHidden == NO) {//tabbar显示时再执行
            //将当前触摸点切换到“大按钮”的坐标系上
            CGPoint pointInBtn = [self convertPoint:point toView:centerBtn];
            if ([centerBtn pointInside:pointInBtn withEvent:event]) {//如果这个点在“大按钮”内部,那么由“大按钮”来响应此事件
                return centerBtn;
            }else {
                return [super hitTest:point withEvent:event];
            }
        }else {
            return [super hitTest:point withEvent:event];
        }
    }
    
    @end
    

    在UITabBarController中用KVC替换一下系统的TabBar

    MyUITabBar *myTabBar = [[MyUITabBar alloc]init];
    myTabBar.centerBtnDelegate = self;
    [self setValue:myTabBar forKeyPath:@"tabBar"];
    

    遵循协议并实现“大按钮”的点击代理方法

    centerButton.png

    相关文章

      网友评论

          本文标题:UITabBar圆形凸起按钮边缘响应点击

          本文链接:https://www.haomeiwen.com/subject/oihbcftx.html