在實(shí)際開發(fā)中經(jīng)常遇到項(xiàng)目中有相同樣式的視圖,我們就可以自定義一個xib視圖在不同的地方使用楼肪。demo傳送門custom-xib-example
1.新建一個繼承UIView
的類开财,例如HLCustomView
2.新建一個xib,取名和1
中的類名一致HLCustomView.xib
3.【重點(diǎn)】:關(guān)聯(lián)類和xib误褪,選中xib责鳍,選中File's Owner
,Class
填HLCustomView
圖片.png
4.在HLCustomView.h
中加入IB_DESIGNABLE
IB_DESIGNABLE
@interface HLCustomView : UIView
@end
5.在HLCustomView.m
中加入一下代碼(也可以將這段代碼加成Xcode代碼塊)
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self build];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
if (self = [super initWithCoder:coder]) {
[self build];
}
return self;
}
#pragma mark - Private Mehtod
- (void)build
{
UIView *view = nil;
#if TARGET_INTERFACE_BUILDER
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
view = [[bundle loadNibNamed:NSStringFromClass(self.class) owner:self options:nil] firstObject];
#else
view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil] firstObject];
#endif
view.frame = self.bounds;
[self addSubview:view];
}
6.在xib兽间、storyboard中使用历葛。拖一個View將Class
改為HLCustomView
即可
圖片.png
demo傳送門custom-xib-example