#import "CDTabBarController.h"
#import "CDRedViewController.h"
#import "CDGreenViewController.h"
#import "CDTabBarButton.h"
@interface?CDTabBarController ()
/**
?*? 設(shè)置之前選中的按鈕
?*/
@property?(nonatomic, weak) UIButton *selectedBtn;
@end
@implementation?CDTabBarController
- (void)viewDidLoad {
????[super?viewDidLoad];
????//設(shè)置子視圖
????[self?setupChildControllers];
? ? //設(shè)置TabBar
????[self?setupTabBar];
}
- (void)setupChildControllers {
????CDRedViewController *redViewController = [[CDRedViewController alloc] init];
????redViewController.view.backgroundColor? = [UIColor redColor];
????redViewController.tabBarItem.title = @"red";
????//設(shè)置圖片
????redViewController.tabBarItem.image = [UIImage imageNamed:@"tabbar_mainframe"];
????//設(shè)置選中圖片
????redViewController.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_mainframeHL"];
? ? CDGreenViewController *greenViewController = [[CDGreenViewController alloc] init];
????greenViewController.view.backgroundColor = [UIColor greenColor];
????greenViewController.tabBarItem.title = @"green";
????greenViewController.tabBarItem.image = [UIImage imageNamed:@"tabbar_me"];
????greenViewController.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_meHL"];
????self.viewControllers = @[redViewController,greenViewController];
}
- (void)setupTabBar {
????//刪除現(xiàn)有的tabBar
????CGRect rect =?self.tabBar.frame;
????[self.tabBar removeFromSuperview];?//移除TabBarController自帶的下部的條
????UIView *myView = [[UIView alloc] init];
????myView.frame = rect;
????myView.backgroundColor = [UIColor cyanColor];
????[self.view addSubview:myView];
????for?(int?i = 0; i < 2; i++) {
????????CDTabBarButton *button = [[CDTabBarButton alloc] init];
????????NSString?*imageName = [NSString?stringWithFormat:@"tabbar_%d",i];
????????NSString?*imageNameSel = [NSString?stringWithFormat:@"tabbar_%dHL",i];
????????[button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
????????[button setImage:[UIImage imageNamed:imageNameSel] forState:UIControlStateSelected];
????????CGFloat x = i * myView.frame.size.width / 2;
????????button.frame = CGRectMake(x, 0, myView.frame.size.width / 2, myView.frame.size.height);
????????[myView addSubview:button];
????????//設(shè)置按鈕的標記, 方便來索引當前的按鈕,并跳轉(zhuǎn)到相應(yīng)的視圖
????????button.tag = i;
????????[button addTarget:self?action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
????????//設(shè)置初始顯示界面
????????if?(0 == i) {
????????????button.selected =?YES;
????????????self.selectedBtn = button;?//設(shè)置該按鈕為選中的按鈕
????????}
????}
}
//TabBar點擊,切換界面
- (void)clickBtn:(UIButton *)button {
????//1.先將之前選中的按鈕設(shè)置為未選中
????self.selectedBtn.selected =?NO;
????//2.再將當前按鈕設(shè)置為選中
????button.selected =?YES;
????//3.最后把當前按鈕賦值為之前選中的按鈕
????self.selectedBtn = button;
????//4.跳轉(zhuǎn)到相應(yīng)的視圖控制器. (通過selectIndex參數(shù)來設(shè)置選中了那個控制器)
????self.selectedIndex = button.tag;
}?
@end