iOS 封装UITabBarController(一)

现在做项目,差不多都会用到UITabBarController,如果没有好的封装思想会有很多的冗余代码,所有,我这里做了一个简单的封装,但是不是最完整的代码,下一版的博客会更新自定义tabBar的代码;

少说废话上代码:

1.首先创建一个AirVTabBariewController,继承于UITabBarController;

2.创建四个控制器,根据需求设置控制器继承于哪个类;

#import "AirVTabBariewController.h"

@interface AirVTabBariewController ()

@end

@implementation AirVTabBariewController

- (void)viewDidLoad {
    [super viewDidLoad];
     
    AirHomeViewController *home = [[AirHomeViewController alloc] init];
    [self addChildVc:home title:@"首页" image:@"tabbar_home" selectedImage:@"tabbar_home_selected"];
    
    AirMessageCenterViewController *messageCenter = [[AirMessageCenterViewController alloc] init];
    [self addChildVc:messageCenter title:@"消息" image:@"tabbar_message_center" selectedImage:@"tabbar_message_center_selected"];
    
    AirDiscoverViewController *discover = [[AirDiscoverViewController alloc] init];
    [self addChildVc:discover title:@"发现" image:@"tabbar_discover" selectedImage:@"tabbar_discover_selected"];
    
    AirProfileViewController *profile = [[AirProfileViewController alloc] init];
    [self addChildVc:profile title:@"我" image:@"tabbar_profile" selectedImage:@"tabbar_profiler_selected"];
}

/**
 *  封装添加子控制器的方法
 *
 *  @param childVc       控制器
 *  @param title         标题
 *  @param image         正常状态下的的图标
 *  @param selectedImage 选中状态下的图标
 */
- (void)addChildVc:(UIViewController *)childVc title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage
{
    //设置标题
    childVc.tabBarItem.title = title;
    childVc.tabBarItem.image = [UIImage imageNamed:image];
    
    //需要设置照片的模式,用照片原图,默认是蓝色的
    childVc.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    //创建修改字体颜色的字典,同时可以设置字体的内边距;
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor colorWithRed:123/255 green:123/255 blue:123/255 alpha:1];
    NSMutableDictionary *selectedTextAttrs = [NSMutableDictionary dictionary];
    selectedTextAttrs[NSForegroundColorAttributeName] = [UIColor orangeColor];
    [childVc.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    [childVc.tabBarItem setTitleTextAttributes:selectedTextAttrs forState:UIControlStateSelected];
    childVc.view.backgroundColor = [UIColor yellowColor];
    
    //不要忘记添加到父控制器上
    [self addChildViewController:childVc];
}

@end

运行效果如下图:



如果转载请注明转于:AirZilong的博客

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值