![](https://img.haomeiwen.com/i3255919/8ada9b52af3005d5.jpg)
如图所示:XIB可以直接设置一些属性,不需要用代码赋值,很方便。那么我们自定义的组件能否也将一些关键的属性放在这里直接填写呢?当然可以啦
首先说下,如果我们不将自定义view的属性放在这里,我们有什么方式对属性进行赋值呢?
第一种方法(最笨的方法)
将自定义组件拖到代码中,直接用代码进行赋值。
第二种方法
CB0FF0B941BBC0D8C7A0E63BCBD69D8C.jpg
如图,在划线处点加号,keypath输入属性名,type输入字段类型,value输入我们需要的值。
总的来说,都比较麻烦。所以我们想到如何设置自有属性
上代码
@interface TopSelectButton : NSButton
@property (nonatomic,strong) IBInspectable NSString *customTitle;
@property (nonatomic,strong) IBInspectable NSImage *customImage;
@property (nonatomic,assign) IBInspectable BOOL isSelected;
@end
如上代码,我只加了一个关键字IBInspectable
,此时,在xib中就会有我们需要的属性如图:
165E8778AAE6E1C5BADD6622600EFA7E.jpg
细心的同学会发现,他的实现就是我们的上述方法二
9FBB84551497F1D0F807076DAA9FDE6E.jpg
顺带讲讲用法吧:
这里设置完了,就好了吗?并没有!那么该如何调用呢?
我们知道XIB调用我们自定义的控件时,会走这个方法
- (void)awakeFromNib{
[super awakeFromNib];
}
所以我们要在这里面进行使用我们需要的属性,如下:
- (void)awakeFromNib{
[super awakeFromNib];
self.wantsLayer = YES;
if (self.customImage != nil) {
NSImageView *iv = [[NSImageView alloc] initWithFrame:CGRectMake(33, 31, 17, 18)];
iv.image = self.customImage;
[self addSubview:iv];
}
if (self.customTitle != nil) {
NSTextField *text = [[NSTextField alloc] initWithFrame:CGRectMake(60, 32, 60, 20)];
[text setEditable:NO];
[text setBezeled:NO];
text.backgroundColor = [NSColor clearColor];
text.stringValue = self.customTitle;
text.textColor = [NSColor whiteColor];
[self addSubview:text];
}
//设置背景色
self.wantsLayer = YES;
if (self.isSelected) {
self.layer.backgroundColor = [NSColor colorWithHexColorString:@"385DC7"].CGColor;
}else{
self.layer.backgroundColor = [NSColor clearColor].CGColor;
}
}
话说,我这里是将文字、图片声明成一个个属性,并没有直接将textfield、imageview声明成属性。感兴趣的可以试一下,直接声明控件,会不会更好用。
好了,致此,所有知识点讲完了。
网友评论