自定义标签工具栏

来源:互联网 发布:淘宝总公司投诉电话 编辑:程序博客网 时间:2024/05/01 08:57

首先创建三级控制器

隐藏默认生成的工具栏

//自定义标签工具栏

- (void)_initTabbarView {


    //(1)隐藏默认生成的工具栏

    self.tabBar.hidden =YES;

    

    //(2)创建视图

    CGFloat height = [UIScreenmainScreen].bounds.size.height;

    CGFloat width = [UIScreenmainScreen].bounds.size.width;

   tabbarView = [[UIViewalloc] initWithFrame:CGRectMake(0, height-49, width,49)];

    //设置背景颜色

    tabbarView.backgroundColor = [UIColorcolorWithPatternImage:[UIImageimageNamed:@"navbg"]];

    [self.viewaddSubview:tabbarView];

    

    //(3)添加按钮

    

    //每一个按钮的宽度

   CGFloat w =  width/5;

    

   for (int i=1; i<6; i++) {

       //创建按钮

        UIButton *button = [UIButtonbuttonWithType:UIButtonTypeCustom];

        button.tag = i-1;

       //设置图片

       NSString *imgName = [NSStringstringWithFormat:@"%d",i];

        [button setImage:[UIImageimageNamed:imgName] forState:UIControlStateNormal];

        //设置frame

        button.frame =CGRectMake((w-42)/2+w*(i-1),2, 42, 45);

        //添加一个点击事件

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

        [tabbarViewaddSubview:button];

    }

    

    //4.创建选中图片

   _selectedImg = [[UIImageViewalloc] initWithFrame:CGRectMake((w-53)/2.0,2, 53, 45)];

   _selectedImg.image = [UIImageimageNamed:@"选中"];

    [tabbarView addSubview:_selectedImg];

    

}


/按钮的点击事件

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


    //切换视图控制器

   self.selectedIndex = button.tag;

    

   //动画

    [UIViewbeginAnimations:nilcontext:nil];

    [UIViewsetAnimationDuration:.2];

    

   _selectedImg.center = button.center;

    

    [UIViewcommitAnimations];

    

}

第二种是直接移除工具栏上的子视图


//2.自定义工具栏的方法

- (void)_newInitTabbar {


    //(1)移除工具栏上的按钮

    //取得tabbar上的所有子视图

   NSArray *views = [self.tabBarsubviews];

   for (UIView *viewin views) {

        [view removeFromSuperview];

    }

    

    //(2)设置背景

    self.tabBar.backgroundImage = [UIImageimageNamed:@"navbg"];

    

    //(3)创建按钮

    CGFloat width = [UIScreenmainScreen].bounds.size.width;

    //每一个按钮的宽度

   CGFloat w =  width/5;

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

        UIButton *button = [UIButtonbuttonWithType:UIButtonTypeCustom];

       NSString *imageName = [NSStringstringWithFormat:@"%d",i+1];

        [button setImage:[UIImageimageNamed:imageName] forState:UIControlStateNormal];

        //设置frame

        button.frame =CGRectMake((w-42)/2+w*i,2, 42, 45);

        //添加一个点击事件

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

        [self.tabBaraddSubview:button];

    }

    

    //(4)创建选中图片

    _selectedImg = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"选中"]];

   _selectedImg.frame =CGRectMake((w-53)/2.0,2, 53, 45);

    [self.tabBaraddSubview:_selectedImg];

    

}



0 0
原创粉丝点击