iOS xib中掌设你的代码 SDK详解之IBInspectable和IB_DESIGNABLE-Storyboad动态刷新🀄️

前言:
在做应用的UI设计的时候,如果属性能够在Interface Builder的图形化界面进行设置,并且动态的预览到效果,那样无疑会大大提高应用的开发效率。而XCode为我们提供了这样的一种方式,就是使用IBInspectable和IB_DESIGNABLE
如图


User Defined Rumtime Attributes

通过User Defined Rumtime Attributes可以在Interface Builder中,设置一些KVC属性的值。例如
设置圆角为50

这样,在运行模拟器,会有如下效果

不过,这样做有明显的弊端

不容易调试和后期维护


IB_DESIGNABLE

IB_DESIGNABLE的宏的功能就是让XCode动态渲染出该类图形化界面。
使用方式,把该宏加在自定义类的前面

#import 
IB_DESIGNABLE
@interface IBDesigbableImageview : UIImageView
@end

然后,再设置imageview为继承类,并且设置圆角

可以看到,storyboard上的imageview动态刷新了


IBInspectable

让支持KVC的属性能够在Attribute Inspector中配置。
不熟悉KVC的童鞋可以看看我这篇文章
ios SDK详解之KVC


添加属性以及Set方法即可,如果是现有类,使用Category

例如为imageView的继承类设置cornerRadius
头文件添加属性

@property (nonatomic) IBInspectable CGFloat cornerRadius;

.m文件实现对应set的方法

-(void)setCornerRadius:(CGFloat)cornerRadius{
    _cornerRadius = cornerRadius;
    self.layer.cornerRadius = cornerRadius;
    self.layer.masksToBounds = cornerRadius > 0?true:false;
}

这样,在Attribute Inspector就会多出一个配置选项

通过设置这个选项,就可以设置layer的圆角了。
每次设置圆角,都会在Identity Inspector中改变一个rumtime的KVC变量

不过,现在仍然不能动态刷新


通过IB_DESIGNABLE配合IBInspectable可以实现动态刷新

实现方式很简单,就是在自定义类的头文件处加上这个宏定义即可。然后把对应的类设置为自定义的类。

.h文件

#import 
IB_DESIGNABLE
@interface IBDesigbableImageview : UIImageView
@property (nonatomic) IBInspectable CGFloat cornerRadius;
@end

.m文件

#import IBDesigbableImageview.h

@implementation IBDesigbableImageview

-(void)setCornerRadius:(CGFloat)cornerRadius{
    _cornerRadius = cornerRadius;
    self.layer.cornerRadius = cornerRadius;
    self.layer.masksToBounds = cornerRadius > 0?true:false;
}

@end

效果就是最开始的Demo


如果不能动态刷新,重启XCode,如果还不能刷新,如下图RefreshingAllViews,建议开启Automatically Refresh Views

 

补充一点的就是日过你想自己写好的代码在xib中中掌设 那么你可以把代码写在

-(void)layoutSubviews中

posted @ 2017-03-08 14:08  谢小锋  阅读(512)  评论(0编辑  收藏  举报