oc中使用IB_DESIGNABLE和IBInspectable
swift中使用@IBDesignable和@IBInspectable
IB_DESIGNABLE声明在类上,IBInspectable声明在属性上
IB_DESIGNABLE
@interface DesignDemoView : UIView
@property(nonatomic,assign) IBInspectable CGFloat scale;
IB_DESIGNABLE和IBInspectable两个效果不同,IB_DESIGNABLE用于将drawrect中写的效果显示在storyboard或者xib上,IBInspectable是在storyboard或者xib上添加一个可修改的属性
首先创建一个DesignDemoView类
头文件声明属性
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface DesignDemoView : UIView
@property(nonatomic,assign) IBInspectable CGFloat cornerRadiu;
@end
//重写setter方法,用于设置圆角
-(void)setCornerRadiu:(CGFloat)cornerRadiu{
self.layer.cornerRadius=cornerRadiu;
self.layer.masksToBounds=YES;
}
//重写drawrect,在xib中会直接显示出hello
-(void)drawRect:(CGRect)rect{
UIFont * font =[UIFont systemFontOfSize:15];
[@"hello" drawInRect:CGRectMake(50, 10, 100, 100) withAttributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:[UIColor orangeColor]}];
}
xib中添加一个view,并设置custom class为DesignDemoView
shot.png
IBInspectable给DesignDemoView类添加了一个cornerRadiu属性,可以用于修改圆角
shot.png
最后显示效果如下
shot.png
网友评论