UIStoryboard这个东西让人又爱又恨,有些大触执着使用纯代码布局,而很多和我一样的新手还是更加喜欢这种相对简单虽然有很多麻烦的小公举。
UIStoryboard里通过IB可以配置很多属性,比如给一个UIButton设置tittle、image。
而当给控件设置圆角的时候,我们需要使用到KeyPath方法,原理和代码的是一样的,只是给了开发者直接在UIStoryboard上的自定义空间。
此处的KeyPath和代码中的是一毛一样的,所以我们完全可以利用它做“任何事”。
下面是我的方式:
创建一个NSObject的分类,我的叫“NSObject+KeypathForSB”。(其实好像弄UIView的分类比较靠谱点,不过我这里直接偷懒用了超级父类)
NSObject+KeypathForSB.h
在.h中只是注释 用来标识一些自己用到的KeyPath
#import@interface NSObject (KeypathForSB)
// 利用sb中的keypath设定一下自定义属性或调用部分方法
/**
* Key Path : backgroundColorForHl
* Type : UIColor
* Object : UIButton
*/
/**
* Key Path : backgroundColorForSl
* Type : UIColor
* Object : UIButton
*/
/**
* Key Path: borderColor
* Type : UIColor
* Object : UIView
*/
/**
* Key Path: placeholderColor
* Type : UIColor
* Object : UITextField
*/
@end
NSObject+KeypathForSB.m
#import "NSObject+KeypathForSB.h"
#import "UIImage+Custom.h"
@implementation NSObject (KeypathForSB)
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
if ([self isKindOfClass:[UIButton class]]) {
[self buttonHandleWithKey:key value:value];
}
if ([self isKindOfClass:[UIView class]]) {
[self viewHandleWithKey:key value:value];
}
if ([self isKindOfClass:[UITextField class]]) {
[self textFieldHandleWithKey:key value:value];
}
}
#pragma view
- (void)viewHandleWithKey:(NSString *)key value:(id)value {
UIView *view = (UIView *)self;
if ([key isEqualToString:@"borderColor"]) {
UIColor *color = (UIColor *)value;
view.layer.borderColor = color.CGColor;
}
}
#pragma button
- (void)buttonHandleWithKey:(NSString *)key value:(id)value {
UIButton *btn = (UIButton *)self;
if ([key isEqualToString:@"backgroundColorForHl"]) {
[btn setBackgroundImage:[UIImage createImageWithColor:value] forState:UIControlStateHighlighted];
}
if ([key isEqualToString:@"backgroundColorForSl"]) {
[btn setBackgroundImage:[UIImage createImageWithColor:value] forState:UIControlStateSelected];
}
}
#pragma textField
- (void)textFieldHandleWithKey:(NSString *)key value:(id)value {
UITextField *tf = (UITextField *)self;
if ([key isEqualToString:@"placeholderColor"]) {
[tf setValue:value forKeyPath:@"placeholderLabel.textColor"];
}
}
@end
在.m实现中,我就是利用了“- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key”这个方法,在UIStoryboard里写自定义KeyPath然后在上述方法中分门别类地执行自己想要的操作。
PS:此法在作为LaunchScreen的UIStoryboard中是无效的