完美封装 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

完美封装 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

完美封装 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];
    }
}

你可能感兴趣的:(iOS)