本文主要是介绍完美封装 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
解决方案: 布局子控件地方, 将中间按钮 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
解决方案: 重写系统的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];}
}
这篇关于完美封装 tabBar 自定义加号按钮的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!