iOS App 換膚方法 - 本地?fù)Q膚

說到主題切換,那么久要做到切換主題瞬間,使所有相關(guān)的界面都發(fā)生變化,這就需要一種機(jī)制來將主題切換這是事件跑出來,并且接受主題切換事件的相關(guān)View 做出相應(yīng)的改變。想到這里你肯定也想到了NSNotification。沒錯,這就是個不錯的選擇,很適合我們的場景。下面具體來實現(xiàn)下。

不管是本地?fù)Q膚還是動態(tài)換膚都需要一個Manager 進(jìn)行初始化主題模式,一半情況下都使用單例初始化就可以。

YNThemeManager.h

主要提供這幾個方法:

  • (void)setupThemeNameArray:(NSArray *)array; 是用來初始化主題模式名稱的, 例如我們初始化兩個本地資源文件 YNTheme-White 和 YNTheme-Black 是bundle文件名稱
[[YNThemeManager sharedInstance] setupThemeNameArray:@[@"YNTheme-White", @"YNTheme-Black"]];

-- (BOOL)changeTheme:(NSString *)themeName; 用來改變主題模式的,在實際使用中只需要將已有的bundle名稱傳入即可

[[YNThemeManager sharedInstance] changeTheme:@"YNTheme-White"];
  • + (UIColor *)colorWithID:(NSString *)colorID;用來獲取顏色
  • + (UIImage *)imageWithName:(NSString *)imageName;用來獲取圖片

YNThemeManager.m

1.初始化

+ (instancetype)sharedInstance{
    
    static YNThemeManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[YNThemeManager alloc] init];
    });
    return manager;
}

2.首先申明幾個屬性
bundle colorsMap themeArray

/** 主題bundle*/
@property (nonatomic,strong) NSBundle *bundle;
/** 顏色對照表*/
@property (nonatomic, copy) NSDictionary *colorsMap;
/** 主題數(shù)組*/
@property (nonatomic, copy) NSArray *themeArray;

3.主題數(shù)組賦值

- (void)setupThemeNameArray:(NSArray *)array{
    self.themeArray = array;
}

4.改變主題.m實現(xiàn)

- (BOOL)changeTheme:(NSString *)themeName{
    /** 判斷當(dāng)前切換主題是否在主題數(shù)組中*/
    if (![_themeArray containsObject:themeName]) {
        return NO;
    }
    /** 獲取bundle路徑*/
    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:themeName withExtension:@"bundle"]];
    if (!bundle) {
        return NO;
    }
    /** 獲取bundle下plist文件路徑*/
    NSString *mapPath = [bundle pathForResource:@"ColorsMap" ofType:@"plist"];
    if (!mapPath) {
        return NO;
    }
    /** 獲取字典*/
    NSDictionary *colorsMap = [NSDictionary dictionaryWithContentsOfFile:mapPath];
      /** 賦值*/
    _themeName = themeName;
    self.bundle = bundle;
    self.colorsMap = colorsMap;
    /** 發(fā)送修改通知*/
    [self sendChangeThemeNotification];
    return YES;
}
/** 發(fā)送修改通知*/
- (void)sendChangeThemeNotification {
    [[NSNotificationCenter defaultCenter] postNotificationName:YNThemeChangeNotification object:nil];
}

5.獲取顏色

+ (UIColor *)colorWithID:(NSString *)colorID{
    if (!colorID) {
        return [UIColor clearColor];
    }
    return [UIColor yn_colorWithHexString:[[self class] colorStringWithID:colorID]];
}
/** 用來查找plist 文件中對應(yīng)色值的value */
+ (NSString *)colorStringWithID:(NSString *)colorID{
    
    NSArray *array = [colorID componentsSeparatedByString:@"_"];
    NSAssert(array.count > 1,  @"未找到對應(yīng)顏色-%@", colorID);
    NSDictionary *colorDict = [[YNThemeManager sharedInstance].colorsMap valueForKeyPath:array[0]];
    NSString *value = colorDict[colorID][@"Color"];
    NSAssert(value, @"未找到對應(yīng)顏色-%@", colorID);
    return value;
}

6.獲取圖片

+ (UIImage *)imageWithName:(NSString *)imageName {
    if (!imageName) {
        return nil;
    }
    NSBundle *bundle = [YNThemeManager sharedInstance].bundle;
    UIImage *image = [UIImage imageNamed:imageName inBundle:bundle compatibleWithTraitCollection:nil];
    NSAssert(image, @"未找到對應(yīng)圖片-%@", imageName);
    
    return image;
}
  • 首先,控制器中的控件比較多,改變起來邏輯相當(dāng)復(fù)雜,邏輯可能不是很清楚
  • 其次就是VC 中有些View 有很多層次,如;VC 中有一個HeaderView ,HeaderView中有BlackView,BlackView 中又有ImageView ,ImageView 中可能還有其他控件,如果要是在主題切換時改變ImageView,面臨的問題就是
    VC ---->HeaderView -----> BlackView ---->ImageView
    這么長的一個通知鏈。估計寫起來會忍不住吐槽。同時維護(hù)起來也是很大的問題。
基于以上問題,我改變了設(shè)計思路,決定采用系統(tǒng)控件主動接受通知。因此想到了對控件做手腳,以Label為例,為UILabel搞一個主題擴(kuò)展
  • 大家可以看到其中有換膚屬性theme_textColor ,如下圖,我們在屬性theme_textColor 的Setter方法中有根據(jù)主題配置調(diào)用系統(tǒng)的相應(yīng)方法,然后對控件注冊監(jiān)聽,等切換主題之后就會收到通知,然后執(zhí)行theme_didChanged方法,為控件設(shè)置正確的主題UI下面直接上代碼:
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UILabel (YNTheme)

@property (nonatomic, copy) NSString *theme_textColor;

@property (nonatomic, copy) NSAttributedString *theme_attributedText;

@end

NS_ASSUME_NONNULL_END
@implementation UILabel (YNTheme)

- (void)theme_didChanged {
    [super theme_didChanged];
    if (self.theme_textColor) {
        self.textColor = [YNThemeManager colorWithID:self.theme_textColor];
    }
    if (self.attributedText) {
        self.attributedText = self.attributedText.theme_replaceRealityColor;
    }
}

// MARK:  ================ Setters ===========================
- (void)setTheme_textColor:(NSString *)color {
    self.textColor = [YNThemeManager colorWithID:color];
    objc_setAssociatedObject(self, @selector(theme_textColor), color, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self theme_registChangedNotification];
}

- (void)setTheme_attributedText:(NSAttributedString *)attributedText {
    self.attributedText = attributedText.theme_replaceRealityColor;
    [self theme_registChangedNotification];
}

- (void)setSDTextColorID:(NSString *)SDTextColorID {
    self.theme_textColor = SDTextColorID;
}

// MARK:  ================ Getters ===========================
- (NSString *)theme_textColor {
    return objc_getAssociatedObject(self, @selector(theme_textColor));
}

- (NSAttributedString *)theme_attributedText {
    return self.attributedText;
}

@end
  • 當(dāng)然這里面會用到通知,我們專門創(chuàng)建一個NSObject+YNTheme分類,用于通知管理,廢話不多說,直接上代碼。
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSObject (YNTheme)

/**
    注冊換膚監(jiān)聽,不會重復(fù)監(jiān)聽
    收到通知后會調(diào)用 theme_didChanged 方法
 */
- (void)theme_registChangedNotification;

/**
    注冊換膚監(jiān)聽,不會重復(fù)監(jiān)聽
    會立即調(diào)用一次 themeChangeBlock,和收到通知后調(diào)用
 */
- (void)theme_observerChangedUsingBlock:(void(^)(id observer))themeChangeBlock;

/** 子類重寫,收到換膚通知會調(diào)用本方法*/
- (void)theme_didChanged;

@end

NS_ASSUME_NONNULL_END
#import "NSObject+YNTheme.h"
#import "YNThemeManager.h"
#import <objc/runtime.h>
#import "NSObject+YNDeallocExecutor.h"

static NSString *const kHasRegistChangedThemeNotification;

@interface NSObject ()

@property (nonatomic, copy) void(^theme_changeBlock)(id observer);

@end

@implementation NSObject (YNTheme)


- (void)theme_registChangedNotification {
    NSNumber *hasRegist = objc_getAssociatedObject(self, &kHasRegistChangedThemeNotification);
    /** 標(biāo)識是否已經(jīng)注冊通知,防止多次設(shè)置后導(dǎo)致同一個控件被注冊多次*/
    if (hasRegist) {
        return;
    }
    objc_setAssociatedObject(self, &kHasRegistChangedThemeNotification, @(YES), OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    /** 接收通知*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(theme_didChanged) name:YNThemeChangeNotification object:nil];
    
    /** 暫時不明白*/
    __weak typeof(self) weakSelf = self;
    [self yn_executeAtDealloc:^{
        [[NSNotificationCenter defaultCenter] removeObserver:weakSelf];
    }];
}
- (void)theme_observerChangedUsingBlock:(void(^)(id observer))themeChangeBlock {
    self.theme_changeBlock = themeChangeBlock;
    [self theme_didChanged];
    [self theme_registChangedNotification];
}

- (void)theme_didChanged {
    if (self.theme_changeBlock) {
        __weak typeof(self) weakSelf = self;
        self.theme_changeBlock(weakSelf);
    }
}

- (void)setTheme_changeBlock:(void (^)(void))block {
    objc_setAssociatedObject(self, @selector(theme_changeBlock), block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)(void))theme_changeBlock {
    return objc_getAssociatedObject(self, @selector(theme_changeBlock));
}
@end
  • 不知道大家發(fā)現(xiàn)沒有這里面涉及到一個 block回調(diào)方法yn_executeAtDealloc這里面具體做什么,容我細(xì)細(xì)道來。
  • 我們在開發(fā)過程經(jīng)常會遇到這樣的情況,我們想監(jiān)測一個NSObject對象到底有沒有釋放掉,通常的做法就是繼承于一個父類在其dealloc方法中進(jìn)行NSLog打印輸出了,這時候我們有沒有思考可以很方便的去實現(xiàn)dealloc方法的捕獲?下面和大家分享一個簡單的方法,來實現(xiàn)這個過程,廢話不多說直接上代碼。
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSObject (YNDeallocExecutor)

- (void)yn_executeAtDealloc:(void (^)(void))block;

@end

NS_ASSUME_NONNULL_END

#import "NSObject+YNDeallocExecutor.h"
#import <objc/runtime.h>

const void *YNDeallocExecutorsKey = &YNDeallocExecutorsKey;

@interface YNDeallocExecutor : NSObject

@property (nonatomic, copy) void(^deallocExecutorBlock)(void);

@end

@implementation YNDeallocExecutor

- (id)initWithBlock:(void(^)(void))deallocExecutorBlock {
    self = [super init];
    if (self) {
        _deallocExecutorBlock = [deallocExecutorBlock copy];
    }
    return self;
}

- (void)dealloc {
    _deallocExecutorBlock ? _deallocExecutorBlock() : nil;
}

@end

@implementation NSObject (YNDeallocExecutor)

- (void)yn_executeAtDealloc:(void (^)(void))block{
    if (block) {
        YNDeallocExecutor *executor = [[YNDeallocExecutor alloc] initWithBlock:block];
        /** 創(chuàng)建一個互斥鎖,保證在同一時間內(nèi)沒有其它線程對self對象進(jìn)行修改,起到線程的保護(hù)作用*/
        @synchronized (self) {
            [[self hs_deallocExecutors] addObject:executor];
        }
    }
}

- (NSHashTable *)hs_deallocExecutors {

    NSHashTable *table = objc_getAssociatedObject(self,YNDeallocExecutorsKey);
    if (!table) {
        table = [NSHashTable hashTableWithOptions:NSPointerFunctionsStrongMemory];
        objc_setAssociatedObject(self, YNDeallocExecutorsKey, table, OBJC_ASSOCIATION_RETAIN);
    }
    return table;
}

@end

以上就是我的換膚思路了,菜鳥小老弟,如有不足,請多多指教!??!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容