iOS 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动态渲染出该类图形化界面。
使用方式,把该宏加在自定义类的前面

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

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

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


IBInspectable

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


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

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

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

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

?
1
2
3
4
5
<code class = "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
<code class = "hljs" objectivec= "" ># import <uikit uikit.h= "" >
IB_DESIGNABLE
@interface IBDesigbableImageview : UIImageView
@property (nonatomic) IBInspectable CGFloat cornerRadius;
@end
</uikit></code>

.m文件

?
1
2
3
4
5
6
7
8
9
10
11
<code class = "hljs" objectivec= "" ># import IBDesigbableImageview.h
 
@implementation IBDesigbableImageview
 
-( 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值