在实际开发中经常遇到项目中有相同样式的视图,我们就可以自定义一个xib视图在不同的地方使用。demo传送门custom-xib-example
1.新建一个继承UIView
的类,例如HLCustomView
2.新建一个xib,取名和1
中的类名一致HLCustomView.xib
3.【重点】:关联类和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
网友评论