說到主題切換飘庄,那么久要做到切換主題瞬間,使所有相關(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