iOS App 換膚方法 - 本地換膚

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

不管是本地換膚還是動態換膚都需要一個Manager 進行初始化主題模式,一半情況下都使用單例初始化就可以。

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;
/** 主題數組*/
@property (nonatomic, copy) NSArray *themeArray;

3.主題數組賦值

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

4.改變主題.m實現

- (BOOL)changeTheme:(NSString *)themeName{
    /** 判斷當前切換主題是否在主題數組中*/
    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;
    /** 發送修改通知*/
    [self sendChangeThemeNotification];
    return YES;
}
/** 發送修改通知*/
- (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 文件中對應色值的value */
+ (NSString *)colorStringWithID:(NSString *)colorID{
    
    NSArray *array = [colorID componentsSeparatedByString:@"_"];
    NSAssert(array.count > 1,  @"未找到對應顏色-%@", colorID);
    NSDictionary *colorDict = [[YNThemeManager sharedInstance].colorsMap valueForKeyPath:array[0]];
    NSString *value = colorDict[colorID][@"Color"];
    NSAssert(value, @"未找到對應顏色-%@", 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, @"未找到對應圖片-%@", imageName);
    
    return image;
}
  • 首先,控制器中的控件比較多,改變起來邏輯相當復雜,邏輯可能不是很清楚
  • 其次就是VC 中有些View 有很多層次,如;VC 中有一個HeaderView ,HeaderView中有BlackView,BlackView 中又有ImageView ,ImageView 中可能還有其他控件,如果要是在主題切換時改變ImageView,面臨的問題就是
    VC ---->HeaderView -----> BlackView ---->ImageView
    這么長的一個通知鏈。估計寫起來會忍不住吐槽。同時維護起來也是很大的問題。
基于以上問題,我改變了設計思路,決定采用系統控件主動接受通知。因此想到了對控件做手腳,以Label為例,為UILabel搞一個主題擴展
  • 大家可以看到其中有換膚屬性theme_textColor ,如下圖,我們在屬性theme_textColor 的Setter方法中有根據主題配置調用系統的相應方法,然后對控件注冊監聽,等切換主題之后就會收到通知,然后執行theme_didChanged方法,為控件設置正確的主題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
  • 當然這里面會用到通知,我們專門創建一個NSObject+YNTheme分類,用于通知管理,廢話不多說,直接上代碼。
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSObject (YNTheme)

/**
    注冊換膚監聽,不會重復監聽
    收到通知后會調用 theme_didChanged 方法
 */
- (void)theme_registChangedNotification;

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

/** 子類重寫,收到換膚通知會調用本方法*/
- (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);
    /** 標識是否已經注冊通知,防止多次設置后導致同一個控件被注冊多次*/
    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
  • 不知道大家發現沒有這里面涉及到一個 block回調方法yn_executeAtDealloc這里面具體做什么,容我細細道來。
  • 我們在開發過程經常會遇到這樣的情況,我們想監測一個NSObject對象到底有沒有釋放掉,通常的做法就是繼承于一個父類在其dealloc方法中進行NSLog打印輸出了,這時候我們有沒有思考可以很方便的去實現dealloc方法的捕獲?下面和大家分享一個簡單的方法,來實現這個過程,廢話不多說直接上代碼。
#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];
        /** 創建一個互斥鎖,保證在同一時間內沒有其它線程對self對象進行修改,起到線程的保護作用*/
        @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

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,818評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,185評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,656評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,647評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,446評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,951評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,041評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,189評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,718評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,602評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,800評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,316評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,045評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,419評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,671評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,420評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,755評論 2 371