//在AppDelegate中寫代碼
//把main.storyBoard刪除后,不再加載,這里需要手動加載window
self.window= [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor= [UIColor whiteColor];
[self.window makeKeyAndVisible];
//在不指定根控制器的情況下,運(yùn)行會崩潰
MyTabBarController *tabBarController = [[MyTabBarControlleralloc] init];
self.window.rootViewController = tabBarController;
//繼承于UITabBarControlle進(jìn)行自定義
[super viewDidLoad];
//加載子視圖控制器
[self loadViewControllers];
//tabBar的層次構(gòu)成
//背景視圖(下)
[self loadCustomTabBar];
//選中視圖(中)
//按鈕(上)
//加載自定義tabBar
- (void)loadCustomTabBar {
//創(chuàng)建tabBar的背景視圖
_bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,HEIGHT- 50,WIDTH, 50)];
_bgView.image = [UIImage imageNamed:@"tabBar"];
//用戶交互性
_bgView.userInteractionEnabled=YES;
[self.view addSubview:_bgView];
//創(chuàng)建選中視圖
_selectedView= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"select"]];
CGFloat eachWidth = WIDTH/_itemsCount;
//默認(rèn)顯示第一個
_selectedView.center =CGPointMake(eachWidth / 2.0, 25);
_selectedView.bounds = CGRectMake(0, 0, 53, 45);
[_bgView addSubview:_selectedView];
//按鈕
for(inti = 0; i <_itemsCount; i ++) {
UIButton *item = [UIButtonbuttonWithType:UIButtonTypeCustom];
item.center =CGPointMake(eachWidth / 2.0 + (eachWidth * i), 25);
item.bounds =CGRectMake(0, 0, 42, 40);
[item setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i + 1]] forState:UIControlStateNormal];
[item addTarget:selfaction:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
item.tag= i + 1;
[_bgView addSubview:item];
}
}
- (void)itemClick:(UIButton*)sender {
//selectedIndex設(shè)置tabBarController選中的子視圖控制器索引
self.selectedIndex = sender.tag-1;
//改變選擇視圖的位置
[UIView animateWithDuration:0.3animations:^{
_selectedView.center = sender.center;
}];
// ???if (sender.tag == 3) {
// ???????[self hidderTabBar];
// ???}
}
//顯示
- (void)showTabBar {
[UIView animateWithDuration:0.3 animations:^{
_bgView.frame =CGRectMake(0,HEIGHT- 50 ,WIDTH, 50);
}];
}
- (void)hidderTabBar {
[UIView animateWithDuration:0.3animations:^{
_bgView.frame=CGRectMake(-WIDTH,HEIGHT- 50 ,WIDTH, 50);
}];
}
- (void)loadViewControllers {
ViewController *vc0 = [[ViewController alloc] init];
ViewController1 *vc1 = [[ViewController1 alloc] init];
ViewController2 *vc2 = [[ViewController2 alloc] init];
ViewController3 *vc3 = [[ViewController3 alloc] init];
ViewController4 *vc4 = [[ViewController4 alloc] init];
NSArray *viewControllers = @[vc0,vc1,vc2,vc3,vc4];
_itemsCount = viewControllers.count;
//把視圖控制器數(shù)組賦值給自身的viewControllers屬性
self.viewControllers = viewControllers;
//隱藏系統(tǒng)的tabBar
self.tabBar.hidden =YES;
}
{
//tabBar背景視圖
UIImageView *_bgView;
//選中視圖
UIImageView *_selectedView;
//子視圖控制器個數(shù)
NSInteger _itemsCount;
}