iOS Tabbar凸起效果

先上效果圖:

之前沒有研究過凸起這種效果,知道項目用到了 纔來仔細研究,之前看似高大上的效果其實實現起來還是挺簡單的。

自定義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!
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章