关于iOS自定义UITabBar的几种方法
#import "CDTabBarController.h"
#import "CDRedViewController.h"
#import "CDGreenViewController.h"
#import "CDTabBarButton.h"
@interface CDTabBarController ()
/**
* 设置之前选中的按钮
*/
@property (nonatomic, weak) UIButton *selectedBtn;
@end
@implementation CDTabBarController
- (void)viewDidLoad {
[super viewDidLoad];
//设置子视图
[self setupChildControllers];
//设置TabBar
[self setupTabBar];
}
- (void)setupChildControllers {
CDRedViewController *redViewController = [[CDRedViewController alloc] init];
redViewController.view.backgroundColor = [UIColor redColor];
redViewController.tabBarItem.title = @"red";
//设置图片
redViewController.tabBarItem.image = [UIImage imageNamed:@"tabbar_mainframe"];
//设置选中图片
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 {
//删除现有的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];
//设置按钮的标记, 方便来索引当前的按钮,并跳转到相应的视图
button.tag = i;
[button addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
//设置初始显示界面
if (0 == i) {
button.selected = YES;
self.selectedBtn = button; //设置该按钮为选中的按钮
}
}
}
//TabBar点击,切换界面
- (void)clickBtn:(UIButton *)button {
//1.先将之前选中的按钮设置为未选中
self.selectedBtn.selected = NO;
//2.再将当前按钮设置为选中
button.selected = YES;
//3.最后把当前按钮赋值为之前选中的按钮
self.selectedBtn = button;
//4.跳转到相应的视图控制器. (通过selectIndex参数来设置选中了那个控制器)
self.selectedIndex = button.tag;
}
@end