代码改变世界

UITabBar的定制

2015-08-25 10:14  薰衣草的陪伴  阅读(172)  评论(0编辑  收藏  举报

在定制UITabBar时要继承与UITabBarController

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

    //1.获取subView

    NSArray *subView = self.tabBar.subviews;

     //2.遍历出subView上所有的

    for (UIView *view in subView) {

        NSLog(@"%@",view);

    }

     //3.UITabBarButton  字符串转换成类

    Class tabBarButton = NSClassFromString(@"UITabBarButton");

     //4.遍历类,如果是按钮 就移除

    for (UIView *item in subView) {

        //判断subViews上的控件是否属于 UITabBarButton类 如果属于将其移除,否则继续循环

        if ([item isKindOfClass:tabBarButton]) {

            [item removeFromSuperview];

        }

    }

    //创建存放tabBar上控件的子视图

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.tabBar.frame.size.height)];

    view.backgroundColor = [UIColor purpleColor];

    [self.tabBar addSubview:view];

     int r  = 3;

    CGFloat padding = (self.tabBar.bounds.size.width - 50 *r) / (r+1);

    for (int i = 0; i < r; i++) {

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

        button.frame = CGRectMake(padding*(i+1)+50*i, 0, 50, self.tabBar.frame.size.height);

        button.backgroundColor = [UIColor orangeColor];

       button.tag = i+100;

        //点击事件

        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

        [view addSubview:button];

    }

 

}

 

//通过tag值找到对应的界面

- (void)buttonAction:(UIButton *)btn{

   self.selectedIndex = btn.tag - 100;

 

}