思路
1.搭建界面,添加兩個(gè)UIView(一個(gè)是TabBar條排惨,子控制器顯示的View)
2.添加子控制器
3.添加按鈕(tabbar上有多少個(gè)按鈕,有子控制器決定)
一.添加子控制器
UIViewController *vc = [[UIViewController alloc]init];
vc.title = @"嘻嘻";
vc.view.backgroundColor = [UIColor orangeColor];
[self addChildViewController:vc];
二.添加按鈕
設(shè)置控制器的個(gè)數(shù)
NSInteger count = self.childViewControllers.count;
設(shè)置按鈕的位置
CGFloat screenW = [UIScreen mainScreen].bounds.size.width;//屏幕的寬度
CGFloat btnW = screenW / count;
CGFloat btnH = self.tabBar.bounds.size.height;
CGFloat btnX = 0;
CGFloat btnY = 0;
添加按鈕的和屬性
for (int i = 0; i < count ?; i++){
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.tag ?= i;
[btn ?setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
UIViewController *vc = self.childViewControllers[i];
[btn setTitle:vc.title forState:UIControlStateNormal];
btnX = i * btnW;
btn.frame = CGRectMake(btnX, btnY, btnW, banh);
[self.tabBar addSubview:btn];
//監(jiān)聽按鈕點(diǎn)擊
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
if (i == 0) {
[self btnClick:btn];
}
}
監(jiān)聽按鈕點(diǎn)擊
- (void)btnClick:(UIButton *)button
{
NSInteger i = button.tag;
_selectedButton.selected = NO;
button.selected = YES;
_selectedButton = button;
//點(diǎn)擊按鈕移除之前的的控制器,添加按鈕對(duì)應(yīng)的控制器
//獲取子控制器
UIViewController *vc = self.childViewControllers[i];
//移除之前的控制器
[self.containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
//添加當(dāng)前控制器
[self.containerView addSubview:vc.view];