UITabBarController的UIViewController动态改变数量

UITabBarControllerUIViewController动态改变数量,即在启动APP后,根据登录用户的权限不同,动态设置UIViewController的显示或隐藏。

实现原理

通过重置`UITabBarController``viewControllers`属性来实现。

示例代码

示例的实现是继承UITabBarController重写了一个BaseTabBarController

// 定义视图控制器可变数组
- (NSMutableArray *)navControllers
{
    if (_navControllers == nil) {
        _navControllers = [[NSMutableArray alloc] init];
        //
        NSArray *vcs = @[self.mainVC, self.addVC, self.mineVC];
        NSArray *vcTitle = @[@"首页", @"加", @"我的"];
        NSArray *vcImage = @[@"homeNormal", @"addNormal", @"mineNormal"];
        NSArray *vcSelected = @[@"homeSelected", @"addSelected", @"mineSelected"];
        //
        for (int index = 0; index < vcs.count; index++) {
            UIViewController *controller = vcs[index];
            NSString *title = vcTitle[index];
            NSString *imageNormal = vcImage[index];
            NSString *imageSelected = vcSelected[index];
            
            controller.title = title;
            controller.tabBarItem.image = [UIImage imageNamed:imageNormal];
            controller.tabBarItem.selectedImage = [UIImage imageNamed:imageSelected];
            // 导航视图控制器
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
            [_navControllers addObject:nav];
        }
    }
    return _navControllers;
}
// 改变视图控制器数量
- (void)reloadVC:(BOOL)isAdd
{   
    if (isAdd) {
        // 增加
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self.discoverVC];
        self.discoverVC.title = @"发现";
        self.discoverVC.tabBarItem.image = [UIImage imageNamed:@"discoverNormal"];
        self.discoverVC.tabBarItem.selectedImage = [UIImage imageNamed:@"discoverSelected"];
        
        [self.navControllers insertObject:nav atIndex:2];
    } else {
        // 删除
        [self.navControllers removeObjectAtIndex:2];
    }
    // 重置改变数量
    self.viewControllers = self.navControllers;
}
// 使用 在AppDelegate中定义成属性
#import <UIKit/UIKit.h>
#import "BaseTabBarController.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (nonatomic, strong) BaseTabBarController *rootVC;

@end
// 调用改变控制的数量
AppDelegate *delegate = (AppDelegate *)UIApplication.sharedApplication.delegate;
[delegate.rootVC reloadVC:YES]; // 新增
[delegate.rootVC reloadVC:NO]; // 删除

你可能感兴趣的:(iOS,开发编码收集)