导航控制器与标签控制器的代码搭建
实现代码
- (void)viewDidLoad {
[super viewDidLoad];
// 1.初始化标签控制器管理的视图控制器
MessageViewController *messageVC = [MessageViewController new];
DynamicViewController *dynamicVC = [DynamicViewController new];
ContactViewController *contactVC = [ContactViewController new];
// 2.将标签控制器管理的视图控制器存入数组中,在后面通过遍历进行统一配置
NSArray *vcs = @[messageVC,contactVC,dynamicVC];
// 3.配置视图控制器数据
NSArray *vcsTitle = @[@"消息",@"联系人",@"动态"];
NSArray *imageNames = @[@"iconfont-xiaoxi.png", @"iconfont-lianxiren.png", @"iconfont-star.png"];
NSArray *selectImageNames = @[@"iconfont-xiaoxi-select.png", @"iconfont-lianxiren-select.png", @"iconfont-star-select.png"];
//创建一个空的可变数组存储导航控制器并交给标签控制器去管理
NSMutableArray *navs = [@[] mutableCopy];
// 4.遍历视图控制器集合统一配置
[vcs enumerateObjectsUsingBlock:^(UIViewController * _Nonnull vc, NSUInteger idx, BOOL * _Nonnull stop) {
//配置tabBarItme
vc.title = vcsTitle[idx];
vc.view.backgroundColor = [UIColor whiteColor];
vc.tabBarItem = [[UITabBarItem alloc]initWithTitle:vcsTitle[idx] image:[UIImage imageNamed:imageNames[idx]] selectedImage:[UIImage imageNamed:selectImageNames[idx]]];
//配置navigationItem
vc.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"菜单" style:UIBarButtonItemStylePlain target:self action:@selector(respondsToNavigationItem:)];
//为视图控制器添加导航栏
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
[navs addObject:nav];
}];
// 5.设置标签控制器管理的视图控制器
self.viewControllers = navs;
self.selectedIndex = 0;
// 设置阴影
self.view.layer.shadowColor = [UIColor colorWithWhite:0.75 alpha:1.f].CGColor;
// 设置阴影偏移量
self.view.layer.shadowOffset = CGSizeMake(-10, 0);
// 设置不透明度
self.view.layer.shadowOpacity = 1.0;
}
注意点:不管怎么使用都需要使用
self.viewControllers = navs;
self.selectedIndex = 0;
上面两端代码用于实现将控制器添加标签栏,相当于navs里面进行了控制器的遍历,且在遍历过程中添加了导航控制器