iOS换肤方案

0.859字数 496阅读 5261
1、方案1
1.1、架构
方案1.png
1.2、实现

(1)设计一套皮肤文件配置协议

ID Value
com.xyz.color.title 0x f f9b6a
com.xyz.color.background 0xf1f2f3
com.xyz.image.button.normal back_n.png
com.xyz.image.button.selected back_s.png
…… ……

(2)扩展基类(NSObject + Theme),缓存对象和方法

// NSObject + Theme
- (NSMutableArray<ActionBloc> *)action {
    NSMutableArray<ActionBloc> *action = objc_getAssociatedObject(self, @selector(action));
    if (!action) {
        // 不存在,则创建关联
        action = [[NSMutableArray alloc] init];
        objc_setAssociatedObject(self, @selector(action), action, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return action;
}

// UIButton + Theme
- (void)them_setImageName:(NSString *)name forState:(UIControlState)state {
    SetImage tmpBlock = ^(){
        UIImage *image = [[ThemEngine sharedInstance] imageForThemeId:name];
        [self setImage:image forState:state];
    };
    
    // 执行
    tmpBlock();
    
    // 缓存方法
    [self.action addObject:[tmpBlock copy]];
}

(3)应用层初始化UI组件,例如UIButton

UIButton *firstBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 120, 75)];
[firstBtn them_setImageName:@"normalImage" forState:UIControlStateNormal];
[[ThemEngine sharedInstance].themUI addObject:firstBtn]; // 缓存对象
[self.view addSubview:firstBtn];

(4)遍历缓存对象和方法,实现换肤

- (void)changeThem {
    for (int i = 0; i< self.themUI.count; i++) {
        NSObject *obj = (NSObject *)[self.themUI objectAtIndex:i];
        [obj.action enumerateObjectsUsingBlock:^(ActionBloc block, NSUInteger idx, BOOL *stop) {
            block();
        }];
    }   
}
2、方案2
2.1、架构
方案2.png
2.2、实现

(1)设计一套皮肤文件配置协议

ID Value
com.xyz.color.title 0x f f9b6a
com.xyz.color.background 0xf1f2f3
com.xyz.image.button.normal back_n.png
com.xyz.image.button.selected back_s.png
…… ……

(2)扩展基类(NSObject+Theme),缓存方法名和参数

- (void)cacheParams:(NSArray *)params forSelector:(SEL)sel
{
    NSMutableDictionary *cachedParams = [self.cachedMethods objectForKey:NSStringFromSelector(sel)];
    
    if (!cachedParams)
    {
        cachedParams = [[NSMutableDictionary alloc] init];
        [self.cachedMethods setObject:cachedParams forKey:NSStringFromSelector(sel)];
    }
    
    /*
     cachedMethods,当前类缓存的方法和参数列表
     {
        selname : // 其中某个方法的参数列表
            {    
            hash : <<[p1, p2, p3]>>,
            hash : <<[p1, p2]>>
        }
     }
     */
    NSString *hashKey = [self hashKeyForParams:params];
    [cachedParams setObject:params forKey:hashKey];
}

(3)扩展UIKit(UIButton+Theme等),新增换肤方法

- (void)setImageWithIdentifier:(NSString *)identifier forState:(UIControlState)state
{
    //  1、注册通知
    [self registerThemeChangeNotification];

    // 2、执行原始方法
    UIImage *image = [ThemeManager sharedManager].themeInfos[identifier];
    [self setImage:image forState:state];
    
    // 3、缓存方法及参数    
    [self cacheParams:@[identifier.imageType, @(state)] forSelector:@selector(setImage:forState:)];
}

(4)ThemeManager发送换肤通知,遍历执行缓存的换肤方法

- (void)performAllCachedSelector
{
   for (NSString *selName in [self.cachedMethods allKeys])
    {
        for (NSArray *params in [self.cachedMethods[selName] allValues])
        {
            [self performSelector:NSSelectorFromString(selName) params:params];
        }
    }
}
3、方案3
3.1、架构
方案3.png
3.2、实现

(1)设计一套皮肤文件配置协议

ID Value
com.xyz.color.title 0x f f9b6a
com.xyz.color.background 0xf1f2f3
com.xyz.image.button.normal back_n.png
com.xyz.image.button.selected back_s.png
…… ……

(2)设计一套方法映射管理协议

Class Selector MapID
UIButton setImage:forState:(normal) kThemeButtonNormalImage
UIButton setImage:forState:(highlighted) kThemeButtonHighlightedImage
UIButton setImage:forState:(selected) kThemeButtonSelectedImage
…… …… ……

(3)扩展UIView(UIView+Theme),添加换肤方法,保存对应关系《MapID — SkinID》

- (void)setThemeMap:(NSDictionary *)themeMap
{  
    // 1、保存对应关系
    objc_setAssociatedObject(self, &kUIView_ThemeMap, themeMap, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    if (themeMap) {
        // 2、注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(themeChanged) name:kThemeDidChangeNotification object:nil];
        
        // 3、执行换肤方法
        [self themeChanged];
    }
    else {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:kThemeDidChangeNotification object:nil];
    }
}

(4)应用层初始化UI组件,例如UIButton

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    btn.themeMap = 
@{kThemeButtonNormalImage : @"com.ac.image.button.normal",
kThemeButtonSelectedImage : @“com.ac.image.button.selected"};
    [self.view addSubview:btn];
}

(5)ThemeManager发送换肤通知,执行换肤方法

- (void)themeChanged
{
    NSDictionary *map = self.themeMap;
    if ([self isKindOfClass:[UIButton class]]) {
       UIButton *obj = (UIButton *)self;
       if (map[kThemeButtonNormalImage]) {
            NSString *skinId = map[kThemeButtonNormalImage];
            UIImage *image = [ThemeManager sharedInstance].themeConfig[skinId];
            [obj setImage:image forState:UIControlStateNormal];
       }
          if (map[kThemeButtonSelectedImage]) {
            NSString *skinId = map[kThemeButtonSelectedImage];
            UIImage *image = [ThemeManager sharedInstance].themeConfig[skinId];
            [obj setImage:image forState:UIControlStateSelected];
       }
    }

    TODO: 遍历执行其他UIKit控件的方法,例如UILabel
}
4、方案对比
4.1、分析

从架构层面来看,这3种方案的实现思路基本一致,具备相同的优点:
(1)利用通知或Block机制,解耦模块;
(2)皮肤文件利用ID特性,方便维护扩展;
(3)利用Category特性,对现有代码改动较小;
唯一的区别在于方法缓存器的设计和实现,这直接影响到换肤框架对App内存的消耗,可通过Demo分析这3种方案的内存占用。

4.2、案例
    // 方案1
    UIButton *testBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 120, 75)];
    [testBtn them_setImageName:@"normalImage" forState:UIControlStateNormal];
    [[ThemEngine sharedInstance].themUI addObject:testBtn]; // 缓存对象
    [self.view addSubview:testBtn];
    
    // 方案2
    UIButton *testBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 120, 75)];
    [testBtn setImageWithIdentifier:@"normalImage" forState:UIControlStateNormal];
    [self.view addSubview:testBtn];
    
    // 方案3
    UIButton *testBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 120, 75)];
testBtn.themeMap = 
@{kThemeButtonNormalImage : @"normalImage"};
    [self.view addSubview:testBtn];

实验结果:

|方案1 |方案2 |方案3
---------|------|--------|------
内存消耗 |752 bytes |472 bytes |372 bytes

4.3、对方案3的改进:提高API的易用性
// 方案3
testBtn.themeMap = 
@{kThemeButtonNormalImage : @"normalImage"};

// 方案3改进
[testBtn setImageWithThemeId:@"normalImage" forState:UIControlStateNormal];
5、参考资料

(1)https://github.com/JyHu/EasyTheme
(2)https://github.com/jiecao-fm/SwiftTheme
(3)https://github.com/yanjunz/ThemeManager

如果读者有更好的方案,欢迎留言,一起讨论。

推荐阅读更多精彩内容