继续上篇iOS AutoLayout: 关联 Xib 和 UIView博客唠叨.
新定义一个 UIView 子类, 名字为 Custom2
新建 xib 文件, 这里取名为 Custom2.xib
看一下视图关系
明显没有设置 File owner
可以看出, 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 实例对象.
来, 运行看一下效果.
怎么刚才设置在 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
运行可以看到效果.