ios 在storyboard 和 xib中,显示自定义view的预览效果

时间:2023-12-18 12:47:14

发现FSCalendar这个控件能在xib中显示预览效果,是怎么实现的呢?其中涉及的知识又有哪些?

主要就是IBInspectable 和 IB_DESIGNABLE

先看 IBInspectable,来个小demo

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic) IBInspectable UIColor *backgroudColor;

@end

这个IBInspectable,就像IBOutlet,能让interface builder 发现这个属性,比较简单,效果如下图,多了一个background color的选项:

ios 在storyboard 和 xib中,显示自定义view的预览效果

再来看看IB_DESIGNABLE,用法也比较简单,但是注意,想让xib 绘制出效果,就要重写 initWithFrame 这个函数(initWithCoder是不对的)。

#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface IBDesignTestView : UIView

@end
#import "IBDesignTestView.h"

@implementation IBDesignTestView

- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIButton *testBtn = [[UIButton alloc] initWithFrame:CGRectMake(, , , )];
testBtn.backgroundColor = [UIColor orangeColor];
[testBtn setTitle:@"testbtn" forState:UIControlStateNormal];
[self addSubview:testBtn];
}
return self;
} // 这个函数是专门为 xib设计的,会在渲染前设置你想要配置的属性。
- (void)prepareForInterfaceBuilder
{
self.backgroundColor = [UIColor blueColor];
} @end

ios 在storyboard 和 xib中,显示自定义view的预览效果