IB_DESIGNABLE 和 IBInspectable 可以让自定义的 UIView 在 Storyboard 或 XIB 中预览和修改一些自定义参数。
- 
IB_DESIGNABLE可以让自定义的UIView在Storyboard或XIB中预览。 - 
IBInspectable可以让自定义UIView的属性出现在Storyboard或XIB的Attributes inspector中。 
自定义一个继承 UIView 的类 SPView
创建一个XIB 文件 SPView.xib ,设置 Class 为 SPView,与之绑定。设置 Size 为 Freeform,调整到合适大小。
image.png
image.png
- 
在类前添加
IB_DESIGNABLE - 
在属性中添加
IBInspectable 
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
IB_DESIGNABLE
@interface SPView : UIView
@property (nonatomic, copy) IBInspectable NSString *text;
@property (nonatomic, assign) IBInspectable CGFloat radius;
@property (nonatomic, strong) IBInspectable UIColor *color;
@property (nonatomic, assign) IBInspectable CGFloat width;
@end
NS_ASSUME_NONNULL_END
在 - (void)drawRect:(CGRect)rect; 方法中实现
#import "SPView.h"
@implementation SPView
- (void)drawRect:(CGRect)rect {
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
    lable.text = self.text;
    lable.textAlignment = NSTextAlignmentCenter;
    lable.font = [UIFont systemFontOfSize:50];
    lable.textColor = UIColor.redColor;
    [self addSubview:lable];
    
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = self.radius;
    self.layer.borderColor = self.color.CGColor;
    self.layer.borderWidth = self.width;
    self.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMaxYCorner;
}
@end
command + B 重新 Build 一下,回到 XIB 文件,Attributes inspector 中出现自定义的属性。
image.png
在自定义的属性中添加值即可预览 view
image.png













网友评论