iOS AutoLayout: 关联 Xib 和 UIView

博客 iOS AutoLayout: 关联 Xib 和 UIViewController 介绍了 UIViewController 如何关联 xib 文件, 并且如何给组件连线以及一些需要注意的事项.

今天继续 Autolayout 的话题.

1.新建一个 Single View 的 iOS 项目

2.新建一个 Empty 的 Userinterface View, 取名为 View.xib

3.新建一个继承自 UIView 的子类, 取名为 CustomView.

4.打开 View.xib, 选择 File Owner 为 CustomView.

如下图所示

图1

在 ViewController 的 viewDidload 加入下面代码:

CustomView *cv = [[CustomView alloc] init];
    UIView *view = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:cv options:nil] firstObject];

    view.frame = self.view.bounds;

    [self.view addSubview:view];

编译运行, 即可看到效果.

CustomView 实现

#import "CustomView.h"

@interface CustomView ()

@property (nonatomic, strong) UIView *nibView;

@end

@implementation CustomView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) {
        _nibView = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil] firstObject];

        _nibView.frame = frame;

        [self addSubview:_nibView];
    }

    NSLog(@"CustomView: initWithFrame...");

    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];

    if (self) {

    }

    NSLog(@"CustomView: initWithCoder...");

    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];

    NSLog(@"CustomView: awakeFromNib...");
}

//重写该方法
- (void)layoutSubviews
{
    [super layoutSubviews];

    self.nibView.frame = self.frame;
}

//重写该方法
- (void)setFrame:(CGRect)frame
{
    _nibView.frame = frame;
    [super setFrame:frame];
}

修改 ViewController 中 viewDidload 方法:

#if 0
    //方式 1
    CustomView *cv = [[CustomView alloc] init];
    UIView *view = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:cv options:nil] firstObject];

    view.frame = self.view.bounds;

    [self.view addSubview:view];
#endif

    // 方式2
    //CustomView *customView = [[CustomView alloc] initWithFrame:self.view.bounds];

    // 方式3
    CustomView *customView = [[CustomView alloc] init];
    customView.frame = self.view.bounds;

    [self.view addSubview:customView]

无论在 ViewController 中使用哪种方式来加载视图, 都是调用视图的 initWithFrame 方法.不是 initWithCoder.

下篇博客继续 UIView 和 Xib 的话题, 我会使用另一种加载和设计方式.

收工!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值