說到主題切換,那么久要做到切換主題瞬間,使所有相關的界面都發生變化,這就需要一種機制來將主題切換這是事件跑出來,并且接受主題切換事件的相關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