三级控制器的概念:UITabBarController- ->(管理) UINavigationController -->(管理) UIViewController
下面笔者就分享一下三级控制器的使用
#import "MainTabbarController.h"
#import "ProfileViewController.h"
#import "GroupViewController.h"
#import "SearchViewController.h"
#import "CommentViewController.h"
#import "MessageViewController.h"
@interface UITabBarController ()
@end
@implementation UITabBarController
- (void)viewDidLoad {
//创建三级控制器
[self _creatView];
//自定义标签工具栏
[self _newInitTabbar];
}
//创建三级控制器- (void)_creatView{
//1.创建视图控制器并把视图控制器添加到数组中
ProfileViewController *profileCtrl = [[[ProfileViewController alloc] init] autorelease];
GroupViewController *groupCtrl = [[[GroupViewController alloc] init] autorelease];
SearchViewController *searchCtrl = [[[SearchViewController alloc] init] autorelease];
CommentViewController *commentCtrl = [[[CommentViewController alloc] init] autorelease];
MessageViewController *messageCtrl = [[[MessageViewController alloc] init] autorelease];
//将视图控制器存放到数组中
NSArray *viewCtrls = @[profileCtrl,groupCtrl,searchCtrl,commentCtrl,messageCtrl];
//2.创建导航控制器并把视图控制器交给导航控制器管理,并且把导航控制器也添加到连一个数组中
NSMutableArray *navCtrls = [[NSMutableArray alloc] init];
for(int i=0; i<5 ; i++) {
//取得视图控制器
UIViewController *viewCtrl = viewCtrls[i];
//创建导航控制器
UINavigationController *navCtrl = [[UINavigationController alloc] initWithRootViewController:viewCtrl];
[navCtrl.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar_bg_normal"] forBarMetrics:UIBarMetricsDefault];
[navCtrls addObject:navCtrl];
}
//3.创建标签控制器,并把导航控制器交给标签控制器管理
self.viewControllers = navCtrls;
}
//自定义标签工具栏
- (void)_newInitTabbar {
//(1)移除工具栏上的按钮
//取得tabbar上的所有子视图
NSArray *views = [self.tabBar subviews];
for (UIView *view in views) {
[view removeFromSuperview];
}
//(2)设置背景
self.tabBar.backgroundImage = [UIImage imageNamed:@"navbg"];
//(3)创建按钮
CGFloat width = [UIScreen mainScreen].bounds.size.width;
//每一个按钮的宽度
CGFloat w = width/5;
for (int i=0; i<5; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *imageName = [NSString stringWithFormat:@"%d",i+1];
[button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
//设置frame
button.frame = CGRectMake((w-42)/2+w*i, 2, 42, 45);
//添加一个点击事件
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.tabBar addSubview:button];
}
//(4)创建选中图片
_selectedImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"选中"]];
_selectedImg.frame = CGRectMake((w-53)/2.0, 2, 53, 45);
[self.tabBar addSubview:_selectedImg];
}
//按钮的点击事件
- (void)buttonAction:(UIButton *)button {
//切换视图控制器
self.selectedIndex = button.tag;
//动画
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.2];
_selectedImg.center = button.center;
[UIView commitAnimations];
}