iOS SDK详解之IBInspectable和IB_DESIGNABLE-Storyboad动态刷新

来源:互联网 发布:翻唱好听的网络女歌手 编辑:程序博客网 时间:2024/06/12 12:06

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


User Defined Rumtime Attributes

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

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

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

不容易调试和后期维护


IB_DESIGNABLE

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

?
1
2
3
4
<codeclass="hljs"objectivec="">#import<uikit uikit.h="">
IB_DESIGNABLE
@interfaceIBDesigbableImageview : UIImageView
@end</uikit></code>

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

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


IBInspectable

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


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

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

?
1
2
<codeclass="hljs"objectivec="">@property(nonatomic) IBInspectable CGFloat cornerRadius;
</code>

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

?
1
2
3
4
5
<codeclass="hljs"objectivec="">-(void)setCornerRadius:(CGFloat)cornerRadius{
    _cornerRadius = cornerRadius;
    self.layer.cornerRadius = cornerRadius;
    self.layer.masksToBounds = cornerRadius > 0?true:false;
}</code>

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

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

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


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

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

.h文件

?
1
2
3
4
5
6
<codeclass="hljs"objectivec="">#import<uikit uikit.h="">
IB_DESIGNABLE
@interfaceIBDesigbableImageview : UIImageView
@property(nonatomic) IBInspectable CGFloat cornerRadius;
@end
</uikit></code>

.m文件

?
1
2
3
4
5
6
7
8
9
10
11
<codeclass="hljs"objectivec="">#importIBDesigbableImageview.h
 
@implementationIBDesigbableImageview
 
-(void)setCornerRadius:(CGFloat)cornerRadius{
    _cornerRadius = cornerRadius;
    self.layer.cornerRadius = cornerRadius;
    self.layer.masksToBounds = cornerRadius > 0?true:false;
}
 
@end</code>

效果就是最开始的Demo


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


0 0