iOS开发

iOS IB_DESIGNABLE 和 IBInspectabl

2020-10-30  本文已影响0人  gaookey

IB_DESIGNABLEIBInspectable 可以让自定义的 UIViewStoryboardXIB 中预览和修改一些自定义参数。



自定义一个继承 UIView 的类 SPView

创建一个XIB 文件 SPView.xib ,设置 ClassSPView,与之绑定。设置 SizeFreeform,调整到合适大小。

image.png image.png
#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
上一篇下一篇

猜你喜欢

热点阅读