IOS 一个继承UITabBarController的子类(UIImageRenderingMode)

前言:很多人用到这个的时候,会问为什么选中的图片不是他们设置的那张图片,究其原因是RenderingMode(渲染)的默认模式是UIImageRenderingModeAutomatic,我们需要将其改为UIImageRenderingModeAlwaysOriginal这个模式。

示例代码如下:

vc.tabBarItem.selectedImage = [[UIImage imageNamed:imagename] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

说一下UIImage的渲染模式:

        UIImage新增了一个只读属性:renderingMode,对应的还有一个新增方法:imageWithRenderingMode:,它使用UIImageRenderingMode枚举值来设置图片的renderingMode属性。该枚举中包含下列值:

  1. UIImageRenderingModeAutomatic  // 根据图片的使用环境和所处的绘图上下文自动调整渲染模式。  
  2. UIImageRenderingModeAlwaysOriginal   // 始终绘制图片原始状态,不使用Tint Color  
  3. UIImageRenderingModeAlwaysTemplate   // 始终根据Tint Color绘制图片,忽略图片的颜色信息。

.h文件

#import 

@interface BasicTabBarController : UITabBarController

@end

.m文件

#import "BasicTabBarController.h"

@interface BasicTabBarController ()

@end

@implementation BasicTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    //1.设置tabBar的背景颜色
    self.tabBar.barTintColor = [UIColor whiteColor];
    //2.字体颜色
    self.tabBar.tintColor = KGlobalBlue;
    //3.添加所有控制器
    [self addSubViewController];
}

#pragma mark 添加所有控制器
- (void)addSubViewController
{
    [self addChildViewControllerWithClassname:@"IWHomeVC" imagename:@"tabbar_home" title:@"首页"];
    [self addChildViewControllerWithClassname:@"IWBusinessVC" imagename:@"tabbar_business" title:@"商家"];
    [self addChildViewControllerWithClassname:@"IWDiscoveryVC" imagename:@"tabbar_discovery" title:@"发现"];
    [self addChildViewControllerWithClassname:@"IWMyVC" imagename:@"tabbar_my" title:@"我的"];
}

#pragma mrak 添加子控制器
- (void)addChildViewControllerWithClassname:(NSString *)classname
                                  imagename:(NSString *)imagename
                                      title:(NSString *)title {
    
    UIViewController *vc = [[NSClassFromString(classname) alloc] init];
    vc.title = title;
    vc.tabBarItem.title = title;
    vc.tabBarItem.image = [UIImage imageNamed:[imagename stringByAppendingString:@"_gray"]];
    vc.tabBarItem.selectedImage = [[UIImage imageNamed:imagename] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self addChildViewController:vc];
}

@end


你可能感兴趣的:(IOS开发)