加载Xib文件

一 .直接加载 xib 文件, 没有.h.m 文件

NSArray *objs = [[NSBundle mainBundle]loadNibNamed:@"XibView" owner:nil options:nil];
UIView *xibView = objs[0];
xibView.backgroundColor = [UIColor redColor];
[self.view addSubview:xibView];
  1. 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值