美文网首页iOS学习笔记
UITabBarController底层实现

UITabBarController底层实现

作者: 小渣渣_闯闯 | 来源:发表于2016-08-03 02:26 被阅读104次

    思路

    1.搭建界面,添加两个UIView(一个是TabBar条,子控制器显示的View)

    2.添加子控制器

    3.添加按钮(tabbar上有多少个按钮,有子控制器决定)

    一.添加子控制器

    UIViewController *vc = [[UIViewController alloc]init];

    vc.title = @"嘻嘻";

    vc.view.backgroundColor = [UIColor orangeColor];

    [self addChildViewController:vc];

    二.添加按钮

    设置控制器的个数

    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 = 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];

    //监听按钮点击

    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

    if (i == 0) {

    [self btnClick:btn];

    }

    }

    监听按钮点击

    - (void)btnClick:(UIButton *)button

    {

    NSInteger i = button.tag;

    _selectedButton.selected = NO;


    button.selected = YES;

    _selectedButton = button;

    //点击按钮移除之前的的控制器,添加按钮对应的控制器

    //获取子控制器

    UIViewController *vc = self.childViewControllers[i];

    //移除之前的控制器

    [self.containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

    //添加当前控制器

    [self.containerView addSubview:vc.view];

    相关文章

      网友评论

        本文标题:UITabBarController底层实现

        本文链接:https://www.haomeiwen.com/subject/ynnxsttx.html