自定义TabBar中间的Item


做一个二次开发的项目,之前TabBar只有4个Item(要求有5个,中间的Item不是系统的Item),中间的Item被遗漏


本来想重新自定义一个TabBar的,但是感觉有点麻烦,然后就试出一种简单的方法,和大家分享一下


将原来的TabBar的viewControllers改为5个,中间的Item,可以随便写一个ViewController,将它的title设置为“”(没有效果,只是需要他的空间)

UITabBarController * tabBar=[[UITabBarController alloc]init];
na3.title = @"";
tabBar.viewControllers = [na1,na2,na3,na4,na5];
然后在TabBar上面创建一个Button(可以是任何控件),放在TabBar的中间(控件一定要添加到TabBar上面)

_midImageButton = [[UIButton alloc]initWithFrame:CGRectMake(HRScreenW/5*2, 0, HRScreenW/5, self.tabBar.frame.size.height)];
[_midImageButton setImage:[UIImage imageNamed:@"mid"] forState:UIControlStateNormal];
[tabBar addSubview:_midImageButton];

然后遵守UITabBarControllerDelegate,执行下面的方法

-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    //如果是点击中间的那个Item,不让它显示对应的ViewController
    UINavigationController * na = (UINavigationController *)viewController;
    if ([na.title isEqualToString:@""]) {
        return NO;
    }
    return YES;
}


然后遵守UITabBarDelegate,执行下面的方法

//选择Item的时候,会执行下面的方法

-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    //如果点击中间那个Item,就弹出一个View
    if ([item.title isEqualToString: @""]) {
        if (_popAddView == nil) {
            _popAddView = [[HRPopAddView alloc]initWithFrame:CGRectMake(0, HRScreenH, HRScreenW, HRScreenH)];
            _popAddView.alpha = 0;
            UIWindow * currentWindow = [UIApplication sharedApplication].keyWindow;
            [currentWindow addSubview:_popAddView];
        }
        [UIView animateWithDuration:0.5 animations:^{
            _popAddView.frame = CGRectMake(0, 0, HRScreenW, HRScreenH);
            _popAddView.alpha = 1;
        }];

    }
}










你可能感兴趣的:(iOS开发,自定义TabBar,TabBar中间的Item)