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 添加到占位视图里面
1 @interface ViewController () 2 @property (weak, nonatomic) IBOutlet UIView *containerView; 3 @property (nonatomic, weak) UIButton *selectedButton; 4 @property (weak, nonatomic) IBOutlet UIView *tabBar; 5 @end 6 7 @implementation ViewController 8 9 - (void)viewDidLoad { 10 [super viewDidLoad]; 11 12 // 添加子控制器 13 UIViewController *vc = [[UIViewController alloc] init]; 14 vc.title = @"全部"; 15 vc.view.backgroundColor = [UIColor orangeColor]; 16 [self addChildViewController:vc]; 17 18 UIViewController *vc1 = [[UIViewController alloc] init]; 19 vc1.title = @"视频"; 20 vc1.view.backgroundColor = [UIColor brownColor]; 21 [self addChildViewController:vc1]; 22 23 UIViewController *vc2 = [[UIViewController alloc] init]; 24 vc2.title = @"图片"; 25 vc2.view.backgroundColor = [UIColor greenColor]; 26 [self addChildViewController:vc2]; 27 28 // 添加按钮 29 [self setupTitleButton]; 30 } 31 #pragma mark - 添加按钮 32 - (void)setupTitleButton 33 { 34 NSInteger count = self.childViewControllers.count; 35 CGFloat screenW = [UIScreen mainScreen].bounds.size.width; 36 CGFloat btnW = screenW / count; 37 CGFloat btnH = self.tabBar.bounds.size.height; 38 CGFloat btnX = 0; 39 CGFloat btnY = 0; 40 for (int i = 0; i < count; i++) { 41 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 42 btn.tag = i; 43 [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 44 [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected]; 45 UIViewController *vc = self.childViewControllers[i]; 46 [btn setTitle:vc.title forState:UIControlStateNormal]; 47 btnX = i * btnW; 48 btn.frame = CGRectMake(btnX, btnY, btnW, btnH); 49 [self.tabBar addSubview:btn]; 50 51 // 监听按钮点击 52 [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]; 53 if (i == 0) { 54 [self btnClick:btn]; 55 } 56 } 57 } 58 59 - (void)btnClick:(UIButton *)button 60 { 61 NSInteger i = button.tag; 62 _selectedButton.selected = NO; 63 button.selected = YES; 64 _selectedButton = button; 65 // 获取子控制器 66 UIViewController *vc = self.childViewControllers[i]; 67 // 移除之前的控制器View 68 [self.containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; 69 // 添加当前控制器的view 70 [self.containerView addSubview:vc.view]; 71 }