iOS开发教程之仿写UITabBarController
程序员文章站
2022-04-30 17:59:37
iOS开发教程之仿写UITabBarController。效果图如下:
知识点:
1. 界面布局, 底部的button和显示的子控制器都分别使用用UIView来存放,方...
iOS开发教程之仿写UITabBarController。效果图如下:
知识点:
1. 界面布局, 底部的button和显示的子控制器都分别使用用UIView来存放,方便后面使用.
2. 使用父子控制器知识,将所有的子控制器添加到ViewController中.
3. 通过遍历ViewController中的子控制器,来给button设置标题.
4. 当点击button的时候,将对应的子控件添加上去.并移除之前的界面( makeObjectPerformSelecter: )
// Created by 朝阳 on 2018/2/2. // Copyright ? 2018年 sunny. All rights reserved. // #import "ViewController.h" #import "SocialViewController.h" #import "HeadLineViewController.h" #import "HotViewController.h" @interface ViewController () /* 管理btn的stack */ @property (weak, nonatomic) IBOutlet UIStackView *btnsView; /* 存放子控制器的View */ @property (weak, nonatomic) IBOutlet UIView *saveChildVcView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1.添加子控制器 [self addChildController]; //2.给按钮设置标题 [self setBtnTitle]; } #pragma -mark 设置按钮的标题 - (void)setBtnTitle { for (NSInteger i = 0; i < self.btnsView.subviews.count; ++i) { UIButton *btn = self.btnsView.subviews[i]; // 获取self中的子控制器.根据子控制器来设置按钮的标题. UIViewController *vc = self.childViewControllers[i]; [btn setTitle:vc.title forState:UIControlStateNormal]; } } #pragma -mark 添加所有子控制器 - (void)addChildController { SocialViewController *socialVC = [[SocialViewController alloc] init]; socialVC.title = @"社会"; [self addChildViewController:socialVC]; HeadLineViewController *headLineVC = [[HeadLineViewController alloc] init]; headLineVC.title = @"头条"; [self addChildViewController:headLineVC]; HotViewController *hotVC = [[HotViewController alloc] init]; hotVC.title = @"热点"; [self addChildViewController:hotVC]; } - (IBAction)btnClick:(UIButton *)sender { // 当显示下一个界面时,移除之前的界面. makeObjectsPerformSelector: 使view中的所有子控制器都执行一次removeFromSuperview方法. [self.saveChildVcView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; // for (UIView *vcView in self.saveChildVcView.subviews) { // [vcView removeFromSuperview]; // } // 把对应子控件的view添加上去 UIViewController *vc = self.childViewControllers[sender.tag]; vc.view.backgroundColor = sender.backgroundColor; vc.view.frame = self.saveChildVcView.bounds; [self.saveChildVcView addSubview:vc.view]; } @end