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 的话题, 我会使用另一种加载和设计方式.

收工!

©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页