iOS AutoLayout: UIView 关联 Xib 不设置 File's Owner

继续上篇iOS AutoLayout: 关联 Xib 和 UIView博客唠叨.

新定义一个 UIView 子类, 名字为 Custom2

新建 xib 文件, 这里取名为 Custom2.xib

看一下视图关系

图1

明显没有设置 File owner

图2

可以看出, Custom2 这个 View 的 Custom Class 是我们上面定义的 Custom2这个 UIView 的子类.

ok, 设置完毕.

将视图上面的元素拖拽到 Custom2这个类中.

代码示例如下:

#import <UIKit/UIKit.h>

@interface Custom2 : UIView

@property (strong, nonatomic) IBOutlet UIImageView *imageView;

@property (strong, nonatomic) IBOutlet UILabel *label;

@end
#import "Custom2.h"

@implementation Custom2

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

    if (self) {
        self.label.backgroundColor = [UIColor redColor];
        self.label.text = @"Successfully.";
    }

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

    return self;
}

@end

在 ViewController 中加载视图

_custom2View = [[NSBundle mainBundle] loadNibNamed:@"Custom2" owner:self options:nil].firstObject;
    _custom2View.frame = self.view.bounds;
    [self.view addSubview:_custom2View];

这里 _custom2View 就是 Custom2 实例对象.

来, 运行看一下效果.

图3

怎么刚才设置在 initWithFrame 里面设置的属性没有生效.

通过调试, 大家可以发现其实 initWithFrame 根本没有被调用.

修改一下 Costom2 的代码

@implementation Custom2

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

    if (self) {
        // 改变背景色
        self.backgroundColor = [UIColor redColor];

        self.label.backgroundColor = [UIColor redColor];
        self.label.text = @"Successfully.";
    }

    NSLog(@"CustomView2: initWithCoder... label: %@", self.label);

    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];

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

@end

再次运行, 你会发现, 背景色是变了, 但是 label 还是没有改变.

这里说明一个问题, xib 加载时候会调用 initWithCoder 方法, 但是子元素(视图)这个时候并没有被实例化.

要想使用这些子元素, 需要在 awakeFromNib 中使用和改变.

@implementation Custom2

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

    if (self) {
        // 改变背景色
        self.backgroundColor = [UIColor redColor];
    }

    NSLog(@"CustomView2: initWithCoder... label: %@", self.label);

    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];

    self.label.backgroundColor = [UIColor greenColor];
    self.label.text = @"Successfully.";

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

@end

运行可以看到效果.

图5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值