简单实现自定义TabBar实现点击tabBarItem触发自定义事件
由于项目中的需求,所以要做自定义的tabBarController来实现点击tabBarItem实现分享和弹出自定义相机实现拍照,那么问题来了,系统自带的tabBarController只能实现页面的跳转,并且在点击tabBarItem时无法隐藏tabBar。那么只好自定义了,在网上查找了很多,发现都不符合自己的需求,所以就自己摸索出了一个,接下来上代码:
- 首先我们创建一个继承UITabBarController的类
-(void)viewDidLoad
{
[super viewDidLoad];
HomeVC *homeVC = [[HomeVC alloc] init];
UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:homeVC];
UserVC *userVC = [[UserVC alloc] init];
UINavigationController *nav3 = [[UINavigationController alloc] initWithRootViewController:userVC];
CameraVC *cameraVC = [[CameraVC alloc] init];
//删除原来的tabbar
CGRect rect = self.tabBar.frame;
[self.tabBar removeFromSuperview]; //移除TabBarController自带的下部的条
//测试添加自己的视图
_myView = [[UIView alloc] init];
_myView.frame = rect;
_myView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_myView];
//这里我只添加了三个controlelr,因为第四个item点击不出现视图,而是触发分享事件
self.viewControllers = @[nav1,cameraVC,nav3];
NSArray *norImgArr = @[@"home01",@"Camera01",@"urse01",@"share01"];
NSArray *selImgArr = @[@"home02",@"Camera02",@"urse02",@"share02"];
for (int i = 0; i < 4; i++)
{
_itemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
float width = MainScreenBounds.size.width/4;
_itemBtn.frame = CGRectMake(i*width+23, 0, 44, 44);
[_itemBtn setBackgroundImage:[UIImage imageNamed:[norImgArr objectAtIndex:i]] forState:UIControlStateNormal];
[_itemBtn setBackgroundImage:[UIImage imageNamed:[selImgArr objectAtIndex:i]] forState:UIControlStateSelected];
_itemBtn.tag = i;
[_itemBtn addTarget:self action:@selector(itemButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[_myView addSubview:_itemBtn];
[self.btnArray addObject:_itemBtn];
}
//设置第一个button为选中状态
((UIButton *)[self.btnArray objectAtIndex:0]).selected = YES;
}
- 接下来是btn的点击事件
- (void)itemButtonClick:(UIButton *)btn
{
self.selectedIndex = btn.tag;
switch (btn.tag)
{
case 0:
{
}
break;
case 1:
{
NSLog(@"照相");
//这里是点击相机的时候隐藏tabbar出现自定义相机界面
_myView.hidden = YES;
}
break;
case 2:
{
}
break;
case 3:
{
NSLog(@"分享");
[self shareButtonClick];
}
break;
default:
break;
}
//点击其他button后第一个button改为非选中状态
((UIButton *)[self.btnArray objectAtIndex:0]).selected = NO;
if (btn != _itemBtn)
{
_itemBtn.selected = NO;
_itemBtn = btn;
}
_itemBtn.selected = YES;
}