直接使用: 😁
-(id)initWithFrame:(CGRect)frame { self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] objectAtIndex:0]; self.frame = frame; return self; }
加载 UIView 的 xib 文件方式有以下几种方式:
一 .直接加载 xib 文件, 没有.h.m 文件
1. NSBundle 方式
NSArray *objs = [[NSBundle mainBundle]loadNibNamed:@"XibView" owner:nil options:nil];
UIView *xibView = objs[0];
xibView.backgroundColor = [UIColor redColor];
[self.view addSubview:xibView];
2. UINib
//一个nib 对象就代表一个 xib 文件
//UINib *nib = [UINib nibWithNibName:@"XibView" bundle:[NSBundle mainBundle]];
//一般 bundle 传nil,默认就是 mainbundle
UINib *nib = [UINib nibWithNibName:@"XibView" bundle:nil];
NSArray *objs = [nib instantiateWithOwner:nil options:nil];
[self.view addSubview:objs[0]];
二. 需要.h .m 文件, 并连线
方式一. 只使用一个 xib
参考: http://www.jianshu.com/p/639fd5f79837
步骤:
1.新建一个view 继承 UIView,命名:XibView
2.新建一个 xib 文件,命名:XibView
3.在 xib 文件中,点击 view(不是设置File's owner), 然后设置右侧Class 选择为 XibView
//此时就可以拖动 xib 中的控件到 XibView的.h 中了
4.外部使用该 view
NSArray *objs = [[NSBundle mainBundle]loadNibNamed:@"XibView" owner:nil options:nil];
XibView *view = objs.firstObject;
[self.view addSubview:view];
方式二. 在一个 xib 中使用另一xib OtherView文件
参考: http://www.jianshu.com/p/9e45590126e4
1.同上 OtherView
2.同上 OtherView
3.在 xib 文件中,点击File owner, 选择右侧Class 为 OtherView, 注意此时不是点击 view
4.将 xib view 拖拽到OtherView的. h文件中
5..被使用的OtherView需要初始化
// initWithCoder为 xib 文件的入口
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
[self addSubview:self.view];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
self.view.frame = self.bounds;
}