LCWechat --完美封装 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];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,046评论 25 709
  • 在iOS开发中经常会涉及到触摸事件。本想自己总结一下,但是遇到了这篇文章,感觉总结的已经很到位,特此转载。作者:L...
    WQ_UESTC阅读 11,297评论 4 26
  • 好奇触摸事件是如何从屏幕转移到APP内的?困惑于Cell怎么突然不能点击了?纠结于如何实现这个奇葩响应需求?亦或是...
    Lotheve阅读 58,739评论 51 604
  • 昨夜里,夜深仍未入眠,翻开手机,发现昆明有雨,乍一惊,才记起3月5日,正值惊蛰。正当时,脑子里跳入五个字——草木一...
    戎十六阅读 3,573评论 0 2
  • 杭城,一座让人想要慢点的城市。 大学毕业后,选择在这里开始,是因为一个重要的人在这个城市。 想来到你在的城市...
    狒狒shi小胖子阅读 1,514评论 0 1