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

运行效果如下图:

iOS 封装UITabBarController(一)_第1张图片


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

你可能感兴趣的:(ios,Objective-C,界面)