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

說到主題切換飘庄,那么久要做到切換主題瞬間,使所有相關(guān)的界面都發(fā)生變化购撼,這就需要一種機(jī)制來將主題切換這是事件跑出來跪削,并且接受主題切換事件的相關(guān)View 做出相應(yīng)的改變。想到這里你肯定也想到了NSNotification迂求。沒錯(cuò)碾盐,這就是個(gè)不錯(cuò)的選擇,很適合我們的場(chǎng)景揩局。下面具體來實(shí)現(xiàn)下毫玖。

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

YNThemeManager.h

主要提供這幾個(gè)方法:

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

-- (BOOL)changeTheme:(NSString *)themeName; 用來改變主題模式的,在實(shí)際使用中只需要將已有的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.首先申明幾個(gè)屬性
bundle colorsMap themeArray

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

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

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

4.改變主題.m實(shí)現(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 文件中對(duì)應(yīng)色值的value */
+ (NSString *)colorStringWithID:(NSString *)colorID{
    
    NSArray *array = [colorID componentsSeparatedByString:@"_"];
    NSAssert(array.count > 1,  @"未找到對(duì)應(yīng)顏色-%@", colorID);
    NSDictionary *colorDict = [[YNThemeManager sharedInstance].colorsMap valueForKeyPath:array[0]];
    NSString *value = colorDict[colorID][@"Color"];
    NSAssert(value, @"未找到對(duì)應(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, @"未找到對(duì)應(yīng)圖片-%@", imageName);
    
    return image;
}
  • 首先驰怎,控制器中的控件比較多阐滩,改變起來邏輯相當(dāng)復(fù)雜,邏輯可能不是很清楚
  • 其次就是VC 中有些View 有很多層次县忌,如叶眉;VC 中有一個(gè)HeaderView ,HeaderView中有BlackView芹枷,BlackView 中又有ImageView ,ImageView 中可能還有其他控件,如果要是在主題切換時(shí)改變ImageView,面臨的問題就是
    VC ---->HeaderView -----> BlackView ---->ImageView
    這么長(zhǎng)的一個(gè)通知鏈莲趣。估計(jì)寫起來會(huì)忍不住吐槽鸳慈。同時(shí)維護(hù)起來也是很大的問題。
基于以上問題喧伞,我改變了設(shè)計(jì)思路走芋,決定采用系統(tǒng)控件主動(dòng)接受通知绩郎。因此想到了對(duì)控件做手腳,以Label為例翁逞,為UILabel搞一個(gè)主題擴(kuò)展
  • 大家可以看到其中有換膚屬性theme_textColor 肋杖,如下圖,我們?cè)趯傩詔heme_textColor 的Setter方法中有根據(jù)主題配置調(diào)用系統(tǒng)的相應(yīng)方法挖函,然后對(duì)控件注冊(cè)監(jiān)聽状植,等切換主題之后就會(huì)收到通知,然后執(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)然這里面會(huì)用到通知津畸,我們專門創(chuàng)建一個(gè)NSObject+YNTheme分類,用于通知管理必怜,廢話不多說肉拓,直接上代碼。
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSObject (YNTheme)

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

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

/** 子類重寫膏执,收到換膚通知會(huì)調(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)識(shí)是否已經(jīng)注冊(cè)通知驻售,防止多次設(shè)置后導(dǎo)致同一個(gè)控件被注冊(cè)多次*/
    if (hasRegist) {
        return;
    }
    objc_setAssociatedObject(self, &kHasRegistChangedThemeNotification, @(YES), OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    /** 接收通知*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(theme_didChanged) name:YNThemeChangeNotification object:nil];
    
    /** 暫時(shí)不明白*/
    __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)沒有這里面涉及到一個(gè) block回調(diào)方法yn_executeAtDealloc這里面具體做什么,容我細(xì)細(xì)道來胧后。
  • 我們?cè)陂_發(fā)過程經(jīng)常會(huì)遇到這樣的情況芋浮,我們想監(jiān)測(cè)一個(gè)NSObject對(duì)象到底有沒有釋放掉,通常的做法就是繼承于一個(gè)父類在其dealloc方法中進(jìn)行NSLog打印輸出了壳快,這時(shí)候我們有沒有思考可以很方便的去實(shí)現(xiàn)dealloc方法的捕獲纸巷?下面和大家分享一個(gè)簡(jiǎn)單的方法,來實(shí)現(xiàn)這個(gè)過程眶痰,廢話不多說直接上代碼瘤旨。
#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)建一個(gè)互斥鎖,保證在同一時(shí)間內(nèi)沒有其它線程對(duì)self對(duì)象進(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

以上就是我的換膚思路了存哲,菜鳥小老弟,如有不足七婴,請(qǐng)多多指教K钔怠!打厘!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末修肠,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子户盯,更是在濱河造成了極大的恐慌嵌施,老刑警劉巖饲化,帶你破解...
    沈念sama閱讀 219,270評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異吗伤,居然都是意外死亡吃靠,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門足淆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來巢块,“玉大人,你說我怎么就攤上這事缸浦∠Τ澹” “怎么了?”我有些...
    開封第一講書人閱讀 165,630評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵裂逐,是天一觀的道長(zhǎng)歹鱼。 經(jīng)常有香客問我,道長(zhǎng)卜高,這世上最難降的妖魔是什么弥姻? 我笑而不...
    開封第一講書人閱讀 58,906評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮掺涛,結(jié)果婚禮上庭敦,老公的妹妹穿的比我還像新娘。我一直安慰自己薪缆,他們只是感情好秧廉,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著拣帽,像睡著了一般疼电。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上减拭,一...
    開封第一講書人閱讀 51,718評(píng)論 1 305
  • 那天蔽豺,我揣著相機(jī)與錄音,去河邊找鬼拧粪。 笑死修陡,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的可霎。 我是一名探鬼主播魄鸦,決...
    沈念sama閱讀 40,442評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼癣朗!你這毒婦竟也來了号杏?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,345評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎盾致,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體荣暮,經(jīng)...
    沈念sama閱讀 45,802評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡庭惜,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了穗酥。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片护赊。...
    茶點(diǎn)故事閱讀 40,117評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖砾跃,靈堂內(nèi)的尸體忽然破棺而出骏啰,到底是詐尸還是另有隱情,我是刑警寧澤抽高,帶...
    沈念sama閱讀 35,810評(píng)論 5 346
  • 正文 年R本政府宣布判耕,位于F島的核電站,受9級(jí)特大地震影響翘骂,放射性物質(zhì)發(fā)生泄漏壁熄。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評(píng)論 3 331
  • 文/蒙蒙 一碳竟、第九天 我趴在偏房一處隱蔽的房頂上張望草丧。 院中可真熱鬧,春花似錦莹桅、人聲如沸昌执。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽懂拾。三九已至,卻和暖如春厂汗,著一層夾襖步出監(jiān)牢的瞬間委粉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工娶桦, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留贾节,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,377評(píng)論 3 373
  • 正文 我出身青樓衷畦,卻偏偏與公主長(zhǎng)得像栗涂,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評(píng)論 2 355