问题:
项目一般中如果我们想给xib中的view动态的设置边框、圆角之类的话,都会用上IBInspectable这个属性,如下:
一般是两种做法
1 弄一个UIView的类目,加上上面的这些属性如下:

2 弄一个UIView的子类,然后再加上这些属性如下:

两种方式大体上是相似的,都需要实现setter方法,在里面用代码设置属性,

在xib面板上都会生成下面面板,然后通过他们设置

但是两者都各有优缺点,像第一种方案,你只需要把类目文件放在工程中,然后任何xib上的view都能生成上面的面板属性,而第二种则必须要与xib上的view关联才可以,如下

但是第二种的好处也是显而易见的,就是可以起到立杆见影的效果,如下

但是我今天要讲的不是上面两种情况,而是IBInspectable的另外一种使用场景,用于你自定义的视图,比如项目中经常会遇到这样一个场景:
项目中可能有多个地方会用到同一个视图(比如显示购物车数量和购物车图标的的视图,我们项目中就有将近十个页面显示这个视图)假如这个视图里面有一个label,现在有这样的需求,在这个页面label是黑色,在另外一个页面label又是红色的,就是存在不同页面这个view里面label对应的颜色不一样的情况,
那么通常的做法是自定义一个View,然后把这个view的label属性暴露出来(或者你不想暴露label,暴露一个titleColor属性出来),然后在每个页面用代码去修改,这种做法应该比较普遍,
但是仔细想一下,这个自定义view我肯定是支持xib的,那么能不能直接在xib上关联这个view的时候,顺便去设置呢,不用每个页面还要用代码写,多麻烦,是吧,这就用到了上面的IBInspectable属性,如下
@interfaceKJCustomView :UIView
@property(nonatomic)IBInspectable UIColor*titleColor;
@property(nonatomic)IBInspectable CGFloat titleFontSize;
@end
- (void)layoutSubviews {
[superlayoutSubviews];
self.kjTitleLable.frame=CGRectMake(10, (self.bounds.size.height-30)/2,self.bounds.size.width-20,30);
self.kjTitleLable.textColor=self.titleColor;
self.kjTitleLable.font= [UIFontsystemFontOfSize:self.titleFontSize];
}
对应的xib上设置如下:

最终结果:

就这么简单,是吧,是不是很方便,demo地址
网友评论