iOS换肤

在开发中常常会遇到换肤的情况,如果每次都用一个判断语句去修改图片会相当的麻烦,为了工作需要我进行了深入研究找到一种方法。

1、创建两个bundle来存放资源文件,里面包含plist文件和图片

iOS换肤_第1张图片

把所需要的图片放进去,plist文件中写对应的颜色

2、写一个配置文件来集中处理图片和颜色

#import "DDSkin.h"

#define SkinColor @"DDDkinColor"

@implementation DDSkin

static NSString *_color;

+ (void)initialize {

// 开始,从沙盒中取之前存储的皮肤颜色

_color = [[NSUserDefaults standardUserDefaults] objectForKey:SkinColor];

if (_color == nil) { // 之前没有存储,取出为空,默认为蓝色

_color = @"blue";

}

}

/**

*  通过该方法可以设置皮肤的颜色

*

*  @param color 皮肤的颜色

*/

+ (void)setSkinColor:(NSString *)color {

_color = color;

// 将用户设置的皮肤颜色进行保存

[[NSUserDefaults standardUserDefaults] setObject:color forKey:SkinColor];

[[NSUserDefaults standardUserDefaults] synchronize];

}

/**

*  通过该方法,可以返回想要的UIImage

*

*  @param name 图片的名称

*

*  @return 当前皮肤对应的UIImage

*/

+ (UIImage *)ddSkinWithImageName:(NSString *)name {

NSString *path = [[NSBundle mainBundle] pathForResource:_color ofType:@"bundle"];

NSString *imagePath = [path stringByAppendingString:[NSString stringWithFormat:@"/%@",name]];

return [[UIImage alloc] initWithContentsOfFile:imagePath];

}

/**

*  返回当前皮肤的Label背景颜色

*

*  @return 当前的背景颜色

*/

+ (UIColor *)ddSkinWithColorName:(NSString *)name {

// 1.获取文件夹位置

NSString *path = [[NSBundle mainBundle] pathForResource:_color ofType:@"bundle"];

//获取文件位置

NSString *plistPath = [path stringByAppendingString:@"/color.plist"];

//读取plist当中的数据

NSDictionary *colorDict = [NSDictionary dictionaryWithContentsOfFile:plistPath];

//将字典当中的值取出

NSString *bgStr = [colorDict objectForKey:name];

//将颜色的字符串截取

NSArray *bgArray = [bgStr componentsSeparatedByString:@","];

//取出颜色的r,g,b数值

CGFloat red = [bgArray[0] floatValue];

CGFloat green = [bgArray[1] floatValue];

CGFloat blue = [bgArray[2] floatValue];

//返回当前皮肤的颜色

return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];

}

@end

3、调用的方法

- (void)viewDidLoad {

[super viewDidLoad];

[self.ragBurron addTarget:self action:@selector(ragButtonTouch) forControlEvents:UIControlEventTouchUpInside];

[self.blueButton addTarget:self action:@selector(blueButtonTouch) forControlEvents:UIControlEventTouchUpInside];

self.blackView.backgroundColor = [DDSkin ddSkinWithColorName:@"color"];

self.imageView.image = [DDSkin ddSkinWithImageName:@"xianxian.jpg"];

}

- (void)ragButtonTouch {

[DDSkin setSkinColor:@"rad"];

self.blackView.backgroundColor = [DDSkin ddSkinWithColorName:@"color"];

self.imageView.image = [DDSkin ddSkinWithImageName:@"xianxian.jpg"];

}

- (void)blueButtonTouch {

[DDSkin setSkinColor:@"blue"];

self.blackView.backgroundColor = [DDSkin ddSkinWithColorName:@"color"];

self.imageView.image = [DDSkin ddSkinWithImageName:@"xianxian.jpg"];

}

4、附GitHub上的demo:https://github.com/wuyezhiguhun/DDSkin

你可能感兴趣的:(iOS换肤)