美文网首页
CustomTabBarController自定义tabBar

CustomTabBarController自定义tabBar

作者: March_Cullen | 来源:发表于2017-03-02 21:25 被阅读0次

    tabBar : view

    // MyTabBarController.h
    
    @interface MyTabBarController : UITabBarController
    @end
    
    // MyTabBarController.m
    
    #import "MyTabBarController.h"
    #import "ViewController.h"
    
    @interface MyTabBarController ()
    {
        NSArray *_vcArray;
        UIButton *_previousBtn;
    }
    @end
    
    @implementation MyTabBarController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        _vcArray = @[@"新闻", @"阅读", @"视听", @"话题", @"我"];
        NSMutableArray *navCs = [NSMutableArray array];
    
        for (NSInteger i = 0; i < _vcArray.count; i ++) {
            ViewController *vc = [[ViewController alloc] init];
            vc.title = _vcArray[i];
            UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:vc];
            [navCs addObject:navC];
        }
        self.viewControllers = navCs;
        [self creatCustomTabBar];
    }
    
    - (void)creatCustomTabBar {
        for (UIView *view in self.tabBar.subviews) {
            [view removeFromSuperview];
        }
    
        for (NSInteger i = 0; i < _vcArray.count; i ++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            if (i == 0) {
                btn.selected = YES;
                _previousBtn = btn;
            }
            btn.frame = CGRectMake(i * self.view.frame.size.width / _vcArray.count, 0, self.view.frame.size.width / _vcArray.count, 49);
            [btn setTitle:_vcArray[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
            btn.titleLabel.font = [UIFont systemFontOfSize:12];
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = 1000 + i;
            [self.tabBar addSubview:btn];
        }
    }
    
    - (void)btnClick:(UIButton *)btn {
        self.selectedIndex = btn.tag - 1000;
        _previousBtn.selected = NO;
        btn.selected = YES;
        [_previousBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        _previousBtn = btn;
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:CustomTabBarController自定义tabBar

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