1.首先要了解:任何控制器,都能添加子控制器
UIViewController里面有一个方法:
- (void)addChildViewController:(UIViewController *)childController;
所有的控制器都继承自UIViewController
2.UITabBarController内部结构和管理原则
2.1 内部结构
UITabBarController内部有两个子控件,一个存放自控制器view的view 一个TabBar条
2.2 管理原则
TabBar上有多少个按钮,由UITabBarController自控制器的个数决定
按钮的内容有对应的子控制器决定
2.3 怎么切换?
点击按钮,就找到按钮对应的控制器,记录当前的按钮
先移除上一个控制器的view,再把当前按钮对应的+控制器的view添加上去
3.自定义UITabBarController的步骤
3.1 搭建界面(1.存放自控制器的view(占位view) 2.UITabBar)
3.2 添加子控制器,把按钮的内容保存到子控制器
3.3 遍历子控制器,给UITabBar添加按钮(给按钮绑定tag 以便区分)
3.4 监听按钮点击,先移除上一个按钮对应的控制器的view,并记录当前的按钮
3.5 监听按钮点击,把按钮对应的子控制器的View 添加到占位视图里面
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (nonatomic, weak) UIButton *selectedButton;
@property (weak, nonatomic) IBOutlet UIView *tabBar;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; // 添加子控制器
UIViewController *vc = [[UIViewController alloc] init];
vc.title = @"全部";
vc.view.backgroundColor = [UIColor orangeColor];
[self addChildViewController:vc]; UIViewController *vc1 = [[UIViewController alloc] init];
vc1.title = @"视频";
vc1.view.backgroundColor = [UIColor brownColor];
[self addChildViewController:vc1]; UIViewController *vc2 = [[UIViewController alloc] init];
vc2.title = @"图片";
vc2.view.backgroundColor = [UIColor greenColor];
[self addChildViewController:vc2]; // 添加按钮
[self setupTitleButton];
}
#pragma mark - 添加按钮
- (void)setupTitleButton
{
NSInteger count = self.childViewControllers.count;
CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
CGFloat btnW = screenW / count;
CGFloat btnH = self.tabBar.bounds.size.height;
CGFloat btnX = ;
CGFloat btnY = ;
for (int i = ; 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, btnH);
[self.tabBar addSubview:btn]; // 监听按钮点击
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
if (i == ) {
[self btnClick:btn];
}
}
} - (void)btnClick:(UIButton *)button
{
NSInteger i = button.tag;
_selectedButton.selected = NO;
button.selected = YES;
_selectedButton = button;
// 获取子控制器
UIViewController *vc = self.childViewControllers[i];
// 移除之前的控制器View
[self.containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
// 添加当前控制器的view
[self.containerView addSubview:vc.view];
}