最近的项目中有需求在tabbar中间添加凸起按钮,并且点击时按钮要旋转,看了仿斗鱼的凸起,点击后是呈现出来的观点,而不是像常规的tabbar上添加一个页面,所以不符合要求,经过一段摸索最后得的一个比较好的效果,下面看效果图
![效果图gif)
# #需求分析
* tabbar有5个项目,每个对应一个页面
*中间项目为凸起按钮
*中间按钮点击后旋转
# #效果实现
*设置5个项目
我们一步步来解决这个问题,首先创建MCTabBarController继承UITabBarController,然后和常规一样创建5个项目,中间的按钮不设置图片,代码如下
//MCTabBarController.m//添加子控制器 - (void) addChildViewControllers {//图片大小建议32 * 32 【自我addChildrenViewController: [[ViewController alloc] init] andTitle: @“首页“andImageName: @“tab1_n”andSelectImage: @“tab1_p”); 【自我addChildrenViewController: [[ViewController alloc] init] andTitle: @“扩展”andImageName: @“tab2_n”andSelectImage: @“tab2_p”);//中间这个不设置东西,只占位 [自我addChildrenViewController: [[ViewController alloc] init] andTitle: @“旋转”andImageName: @”“andSelectImage: @ "); 【自我addChildrenViewController: [[ViewController alloc] init] andTitle: @”发现“andImageName: @“tab3_n”andSelectImage: @“tab3_p”); 【自我addChildrenViewController: [[ViewController alloc] init] andTitle: @“我”andImageName: @“tab4_n”andSelectImage: @“tab4_p”); } - (void) addChildrenViewController:(*) ui childVC andTitle: (NSString *)标题andImageName: (NSString *) imageName andSelectImage: (NSString *) selectedImage { childVC.tabBarItem。形象=[界面图像imageNamed imageName):; childVC.tabBarItem。selectedImage=[界面图像imageNamed selectedImage):; childVC。标题=标题; BaseNavigationController * baseNav=[[BaseNavigationController alloc] initWithRootViewController childVC):; (自我addChildViewController: baseNav); }
这样实现的效果如下图所示
(图一. png]
*添加凸起按钮
我们可以在UITabBar上添加我们的凸起按钮,让他的位置在没有设置的中间按钮偏上,按钮的点击和中间按钮点击绑定,这里直接在MCTabBarController.m中添加会有问题
1,因为凸起按钮的超帧出了UITabBar的框架,这样超出的区域点击按钮会没有响应(图二红框区域),原因和解决办法详情参考我的这篇(iOS UIButton点击无响应的解决办法)(https://www.jb51.net/article/131227.htm),由于要在UITabBar上添加凸起按钮,并且处理点击无效的问题,所以这里创建了MCTabBar继承UITabBar
(图二. png]
2,由于UITabBar是只读的,所以我们不能直接对他进行赋值,这里利用现有的访问私有变量将MCTabBar赋值给“tabBar”
* *具体实现* *
MCTabBar
' ' '
#进口 @ interface MCTabBar: UITabBar @ property(原子、强)UIButton * centerBtn;//中间按钮 @end ' ' ' ' ' ' @ implementation MCTabBar - (instancetype) init { 如果(自我=(超级init)) { (自我initView); } 回归自我; } - (void) initView { _centerBtn=[UIButton buttonWithType UIButtonTypeCustom):;//设定按钮大小为适应图片 用户界面图像* normalImage=[界面图像imageNamed: @“tabbar_add”); _centerBtn.frame=CGRectMake (0, 0, normalImage.size。宽度,normalImage.size.height); [_centerBtn setImage: normalImage forState UIControlStateNormal):;//去除选择时高亮 _centerBtn。adjustsImageWhenHighlighted=没有;//根据图片调整按钮的位置(图片中心在tabbar的中间最上部,这个时候由于按钮是有一部分超出tabbar的,所以点击无效,要进行处理) _centerBtn.frame=CGRectMake (([UIScreen mainScreen] .bounds.size。宽度- normalImage.size.width)/2.0,——normalImage.size normalImage.size.height/2.0。宽度,normalImage.size.height); (自我addSubview: _centerBtn); }//处理超出区域点击无效的问题 ——(UIView *) hitTest: (CGPoint)点withEvent: (UIEvent *)事件{ UIView *视图=(超级hitTest:一点withEvent:事件); 如果(查看==nil) {//转换坐标 CGPoint tempPoint=[自我。centerBtn convertPoint:点fromView:自我);//判断点击的点是否在按钮区域内 如果(CGRectContainsPoint (self.centerBtn。界限,tempPoint)) {//返回按钮 返回_centerBtn; } } 返回视图; } ' ' 'iOS Tabbar中间添加凸起可旋转按钮功能