白天/夜间模式的切换,在万能的github上就有这么一个牛X的库-----DKNightVersion传送门
小Demo
DKNightVersion实现原理(个人猜测)
我觉得DKNightVersion实现的基本原理应该是利用一个单例存储颜色, 通过runtime中的objc_setAssociatedObject 和 objc_getAssociatedObject
来完成对象间传递所要保存的颜色。具体怎么实现的我也不太清楚还没到那层次,还望懂的大神不吝赐教。
下面是简单使用代码
#import "ViewController.h"
#import <DKNightVersion/DKNightVersion.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UISwitch *switchs;
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *leftButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *rightButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self changeColor];
}
// 修改颜色也可以通过设置修改,改成你自己喜换的颜色,在这我是使用了DKNightVersion封装好的
- (void)changeColor
{
UILabel *navLabel = [[UILabel alloc] init];
navLabel.text = @"夜间模式";
[navLabel sizeToFit];
self.navigationItem.titleView = navLabel;
// view的背景颜色
self.view.dk_backgroundColorPicker = DKColorPickerWithKey(BG);
// titleView颜色
navigationLabel.dk_textColorPicker = DKColorPickerWithKey(TEXT);
// 按钮title颜色
[self.button dk_setTitleColorPicker:DKColorPickerWithKey(TINT) forState:UIControlStateNormal];
// 开关颜色
self.switchs.dk_tintColorPicker = DKColorPickerWithKey(TINT);
// 左右item颜色
self.leftButton.dk_tintColorPicker = DKColorPickerWithKey(TINT);
self.rightButton.dk_tintColorPicker = DKColorPickerWithKey(TINT);
}
// button点击事件
- (IBAction)open:(id)sender
{
// 判断当前是否为夜间模式
if ([self.dk_manager.themeVersion isEqualToString:DKThemeVersionNight]) {
// 切换为白天模式
[self.dk_manager dawnComing];
} else {
// 切换为夜间模式
[self.dk_manager nightFalling];
}
}
// 监听switch开/关
- (IBAction)change:(id)sender
{
if (self.switchs.isOn) {
// 打开切换为白天模式
self.dk_manager.themeVersion = DKThemeVersionNight;
}else {
// 关闭切换为夜间模式
self.dk_manager.themeVersion = DKThemeVersionNormal;
}
}
// 左边item点击事件
- (IBAction)left:(id)sender
{
self.dk_manager.themeVersion = @"RED";
}
// 右边边item点击事件
- (IBAction)right:(id)sender
{
self.dk_manager.themeVersion = DKThemeVersionNormal;
}
实现原理(runtime) :http://draveness.me/dknightversion-de-shi-xian-wei-ios-ying-yong-tian-jia-ye-jian-mo-shi.html