UITabBarController(二)自定义UITabBar方式一

来源:互联网 发布:手机淘宝能发布食品吗? 编辑:程序博客网 时间:2024/05/23 00:53

转载自:(http://www.jianshu.com/p/fcf0f6933ffe)

自定义UITabBar代码如下:

// 中间凸起部分的按钮-(UIButton *)centerBtn{    if (_centerBtn == nil) {        _centerBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 90, 90)];        // 禁止按钮在高亮下改变颜色        _centerBtn.adjustsImageWhenHighlighted = NO;        [_centerBtn setImage:[UIImage imageNamed:@"tab_launch"] forState:UIControlStateNormal];        [_centerBtn addTarget:self action:@selector(clickCenterBtn:) forControlEvents:UIControlEventTouchUpInside];    }    return _centerBtn;}- (void)clickCenterBtn:(UIButton *)sender{    NSLog(@"点击中间按钮事件");}// 重写layoutSubviews-(void)layoutSubviews{    [super layoutSubviews];    self.backgroundColor = [UIColor whiteColor];    // 把 tabBarButton 取出来    NSMutableArray *tabBarBtnArr = [NSMutableArray array];    for (UIView *view in self.subviews) {        if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")]) {            [tabBarBtnArr addObject:view];        }    }    CGFloat barWidth = self.bounds.size.width;    CGFloat barHeight = self.bounds.size.height;    CGFloat centerBtnWidth = CGRectGetWidth(self.centerBtn.frame);    CGFloat centerBtnHeight = CGRectGetHeight(self.centerBtn.frame);    // 设置中间按钮的位置,居中,部分凸起    self.centerBtn.center = CGPointMake(barWidth/2, barHeight - centerBtnWidth/2 + 10);    [self addSubview:self.centerBtn];    // 重新布局其他 tabBarItem    // 平均分配其他 tabBarItem 的宽度    CGFloat barItemWidth = (barWidth - centerBtnWidth) / tabBarBtnArr.count;    // 逐个布局 tabBarItem, 修改 UITabBarButton 的 frame    [tabBarBtnArr enumerateObjectsUsingBlock:^(UIView * _Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {        CGRect frame = view.frame;        if (idx >= tabBarBtnArr.count / 2) {            // 重新设置 x 坐标, 如果排在中间按钮的右边需要加上中间按钮的宽度            frame.origin.x = idx * barItemWidth + centerBtnWidth;        } else {            frame.origin.x = idx * barItemWidth;        }        // 重新设置宽度        frame.size.width = barItemWidth;        view.frame = frame;    }];    // 把中间按钮带到视图最前面    [self bringSubviewToFront:self.centerBtn];}// 凸起button原本是接收不到点击事件的,需要重写 hitTest:withEvent: 方法- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{    if (self.clipsToBounds || self.hidden || (self.alpha == 0.f)) {        return nil;    }    UIView *result = [super hitTest:point withEvent:event];    // 如果事件发生在tabbar里面直接返回    if (result) {        return result;    }    // 这里遍历那些超出的部分就可以了,不过这么写比较通用。    for (UIView *subview in self.subviews) {        // 吧这个坐标从tabbar的坐标系转为 subview 的坐标系        CGPoint subPoint = [subview convertPoint:point fromView:self];        result = [subview hitTest:subPoint withEvent:event];        // 如果事件发生在 subview 里就返回        if (result) {            return result;        }    }    return nil;}

OK !最后需要在自定义的UITabBarController的viewDidLoad方法中添加一行代码:

    // 利用KVO来使用自定义的tabBar    [self setValue:[[CustomerBar alloc] init] forKey:@"tabBar"];

最终效果如下:
这里写图片描述

阅读全文
0 0
原创粉丝点击