美文网首页
iOS Tabbar凸起效果

iOS Tabbar凸起效果

作者: 一笔一划_py | 来源:发表于2020-06-24 14:35 被阅读0次

    先上效果图:


    WX20200624-142234.png

    之前没有研究过凸起这种效果,知道项目用到了 才来仔细研究,之前看似高大上的效果其实实现起来还是挺简单的。

    自定义UITabbar:
    只要代码都写在了layoutSubviews方法里,为了让拿到系统“UITabBarButton”的frame

    - (instancetype)initWithBumpIndex:(NSInteger)index bumpHeight:(CGFloat)bumpHeight didTapBumpBarBlock:(DidTapBumpBarBlock)didTapBumpBarBlock{
        if (self = [super init]) {
            _index = index;
            _bumpHeight = bumpHeight;//凸起的高度
            _didTapBumpBarBlock = didTapBumpBarBlock;
            
            _arrTabBarButton = [NSMutableArray array];
        }
        return self;
    }
    - (void)layoutSubviews{
        [super layoutSubviews];
        
        for (id obj in self.subviews) {
            if ([obj isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
                //一个可变数组保存所有的UITabBarButton按钮
                [_arrTabBarButton addObject:obj];
            }
        }
        /**
    循环防止重复创建  也可以把roundView设置成全局的 把初始化方法写在UITabbar 的init方法里就不需要这个循环了
    */
        for (id obj in self.subviews) {
            if ([obj isKindOfClass:[UIControl class]]) {
                UIControl *view = obj;
                if (view.tag == 123456) {
                    [view removeFromSuperview];
                }
            }
        }
        //_index是传进来的需要凸起的index
        UIButton *button = _arrTabBarButton[_index];
        
        UIControl *roundView = [[UIControl alloc]initWithFrame:CGRectMake(button.x, -_bumpHeight, button.width, button.width)];
        roundView.tag = 123456;
        roundView.layer.cornerRadius = roundView.height*0.5;
        roundView.clipsToBounds = YES;
        roundView.backgroundColor = [UIColor whiteColor];
        [roundView addTarget:self action:@selector(tapControl:) forControlEvents:UIControlEventTouchUpInside];
        [self insertSubview:roundView atIndex:0];
    }
    //凸起部分的点击事件
    - (void)tapControl:(UIControl *)control{
        if (_didTapBumpBarBlock) {
            _didTapBumpBarBlock();
        }
    }
    //由于凸起部分在UITabbar frame外 使用该方法解决不能点击到
    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
        //如果不加上这个判断,当push到其他页面点击这个位置也会响应
        if (!self.hidden) {
            UIControl *roundView = [self viewWithTag:123456];
            if (CGRectContainsPoint(roundView.frame, point)) {
                return roundView;
            }
        }
        return [super hitTest:point withEvent:event];
    }
    

    over!

    相关文章

      网友评论

          本文标题:iOS Tabbar凸起效果

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