美文网首页iOS开发
iOS IB_DESIGNABLE 和 IBInspectabl

iOS IB_DESIGNABLE 和 IBInspectabl

作者: gaookey | 来源:发表于2020-10-30 15:21 被阅读0次

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

  • IB_DESIGNABLE 可以让自定义的 UIViewStoryboardXIB 中预览。

  • IBInspectable 可以让自定义 UIView 的属性出现在 StoryboardXIBAttributes inspector 中。



自定义一个继承 UIView 的类 SPView

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

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

相关文章

网友评论

    本文标题:iOS IB_DESIGNABLE 和 IBInspectabl

    本文链接:https://www.haomeiwen.com/subject/nejdvktx.html