完美封装 tabBar 自定义加号按钮

1.自定义TabBarController

1.自定义继承于UITabBarController
2.利用KVC 替换系统的tabBar
3. 利用appearance 全局统一设置UITabBarItem
[self setValue:[[LCTabBar alloc] init] forKeyPath:@"tabBar"];
 NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
  normalAttrs[NSForegroundColorAttributeName] = [UIColor grayColor]; normalAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:12];

  NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
   selectedAttrs[NSForegroundColorAttributeName] = [UIColor darkGrayColor];

 UITabBarItem *item = [UITabBarItem appearance];
  [item setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
  [item setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];

2.自定义tabBar

1.自定义继承于UITabBar
2.初始化
3.布局

2.1中间有线条的tabBar

如图1


1.png

解决方案: 布局子控件地方, 将中间按钮 bringSubviewToFront

- (void)layoutSubviews
{
    [super layoutSubviews];

    CGFloat width = self.width;
    CGFloat height = self.height;

    self.plusButton.center = CGPointMake(width * 0.5, height * 0.5);
    self.plusButton.y = -20;

    int index = 0;

    CGFloat tabBarButtonW = width / 5;
    CGFloat tabBarButtonH = height;
    CGFloat tabBarButtonY = 0;

    for (UIView *tabBarButton in self.subviews) {
        if (![NSStringFromClass(tabBarButton.class) isEqualToString:@"UITabBarButton"]) continue;


        CGFloat tabBarButtonX = index * tabBarButtonW;
        if (index >= 2) {
            tabBarButtonX += tabBarButtonW;
        }


        tabBarButton.frame = CGRectMake(tabBarButtonX, tabBarButtonY, tabBarButtonW, tabBarButtonH);

        index++;
    }

    [self bringSubviewToFront:self.plusButton];
}

2.2中间按钮 超出tabBar的范围不能响应点击事件

如图 2


2.png

解决方案: 重写系统的hitTest方法, 不了解的看官可以去查查事件传递和响应者链条

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

    if (self.isHidden == NO) { // 当前界面 tabBar显示

        CGPoint newPoint = [self convertPoint:point toView:self.plusButton];

        if ( [self.plusButton pointInside:newPoint withEvent:event]) { // 点 属于按钮范围
            return self.plusButton;

        }else{
            return [super hitTest:point withEvent:event];
        }
    }
    else {
        return [super hitTest:point withEvent:event];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值