//在AppDelegate中写代码
//把main.storyBoard删除后,不再加载,这里需要手动加载window
self.window= [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor= [UIColor whiteColor];
[self.window makeKeyAndVisible];
//在不指定根控制器的情况下,运行会崩溃
MyTabBarController *tabBarController = [[MyTabBarControlleralloc] init];
self.window.rootViewController = tabBarController;
//继承于UITabBarControlle进行自定义
[super viewDidLoad];
//加载子视图控制器
[self loadViewControllers];
//tabBar的层次构成
//背景视图(下)
[self loadCustomTabBar];
//选中视图(中)
//按钮(上)
//加载自定义tabBar
- (void)loadCustomTabBar {
//创建tabBar的背景视图
_bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,HEIGHT- 50,WIDTH, 50)];
_bgView.image = [UIImage imageNamed:@"tabBar"];
//用户交互性
_bgView.userInteractionEnabled=YES;
[self.view addSubview:_bgView];
//创建选中视图
_selectedView= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"select"]];
CGFloat eachWidth = WIDTH/_itemsCount;
//默认显示第一个
_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设置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;
//把视图控制器数组赋值给自身的viewControllers属性
self.viewControllers = viewControllers;
//隐藏系统的tabBar
self.tabBar.hidden =YES;
}
{
//tabBar背景视图
UIImageView *_bgView;
//选中视图
UIImageView *_selectedView;
//子视图控制器个数
NSInteger _itemsCount;
}