三級控制器的概念: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];
}