Knight Watson是一款主题管理库,可以轻松地将夜间版本等功能添加到iOS应用中。利用ObjC的运行时,Knight Watson可以通过在其后添加后缀来为实例添加主题。因此,它可以为您节省很多学习新方法的时间。
所有魔法都始于后缀 knw_themable
,然后再剩下的都是熟悉的Cocoa方法。
// Configure the instance with values by theme
//
UIView
*view = [[UIView alloc] init];
view.knw_themable.backgroundColor = (id)@{@"daylight": UIColor.whiteColor,
@"night": UIColor.blackColor,};
// Change the theme sometime later
//
KNWThemeContext.defaultThemeContext.theme = @"night";
如果一个参数符合协议 KNWObjectArgument
,则该参数将被视为主题参数。库中提供了 KNWThemedArgument
类作为示例。查看 knw_valueWithThemeContext:
方法的实现,您可以实现您自己的主题参数。例如,为了将 NSDictionary
作为主题参数,可以这样做
@interface NSDictionary (KNWObjectArgument) <KNWObjectArgument>
@end
@implementation NSDictionary (KNWObjectArgument)
- (id)knw_valueWithThemeContext:(KNWThemeContext *)context
{
return self[context.theme];
}
@end
同样支持非对象参数
UIView
*view = [[UIView alloc] init];
NSDictionary
*framesByTheme =
@{@"theme_a": [NSValue valueWithCGRect:CGRectMake(1., 1., 1., 1.)],
@"theme_b": [NSValue valueWithCGRect:CGRectMake(2., 2., 2., 2.)],};
[view
.knw_themable
.argAtIndex(0, framesByTheme)
setFrame:CGRectZero];
要将非对象值用作主题参数,类必须符合协议 KNWNonObjectArgument
。也可以查看示例方法 KNWThemedArgument#knw_invocation:setArgumentAtIndex:withThemeContext:
的实现。
有时,我们只想得到当前主题的值,而不是随着主题的变化而变化。在这种情况下,我们只需要一行代码
UIView
*view = [[UIView alloc] init];
NSDictionary
*colorsByTheme = @{@"daylight": UIColor.whiteColor,
@"night": UIColor.blackColor,};
[view
.knw_themable
.keepThemable(NO)
setBackgroundColor:(id)colorsByTheme];
或者简单使用方便的后缀(注意后缀已被替换为 knw_themed
)
view.knw_themed.backgroundColor = (id)@{@"daylight": UIColor.whiteColor,
@"night": UIColor.blackColor,};
KNWThemeContext#theme
的类型是 id
。因此,只要您的 KNWObjectArgument
(或 KNWNonObjectArgument
)实现可以处理它,它可以是任何类。例如,如果使用 NSNumber
的实例作为主题,那么数组 NSArray
也可以作为主题参数传递
KNWThemeContext.defaultThemeContext.theme = @1;
UIButton
*button = [[UIButton alloc] init];
NSArray
*colorsByTheme = @[UIColor.whiteColor, UIColor.blackColor,];
[button.knw_themable setTitleColor:(id)colorsByTheme
forState:UIControlStateNormal];
UIButton
,UILabel
,UIImageView
] 支持UIColor
,UIImage
,NSAttributedString
] 支持