一.view的封装:
代码实现:
- (instancetype)init
{
if (self = [super init]) {
// 1.添加UIImageView对象用于显示商品的图片
UIImageView *iconView = [[UIImageView alloc] init];
[self addSubview:iconView];
self.iconView = iconView;
// 2.添加UILabel对象用于显示商品的名字
UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:titleLabel];
self.titleLabel = titleLabel;
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
// 1.取出当前控件的宽度和高度
CGFloat width = self.frame.size.width;
CGFloat height = self.frame.size.height;
// 2.调整子控件的frame
self.iconView.frame = CGRectMake(0, 0, width, width);
self.titleLabel.frame = CGRectMake(0, width, width, height - width);
}
二.Xib和stroyboard对比
加载xib
xib的使用注意:
1.如果一个View是通过xib加载,那么创建View的时候,不能通过 alloc] init] 来创建
2.如果多处都使用xib来创建该View,最好提供一个快速创建的类方法
3.如果一个view是从xib加载出来的,那么不会执行init方法和initWithFrame方法
4.如果一个view是从xib加载出来的,会执行initWithCoder和awakeFromNib方法
// 如果控件时通过xib或者storyboard加载出来的,那么就会执行该方法
// 作用:在initWithCoder方法中添加子控件
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
NSLog(@"%s", __func__);
self.backgroundColor = [UIColor yellowColor];
}
return self;
}
// 所以xib中的控件都加载好之后会执行该方法
// 作用:初始化操作,比如设置背景,初始化一些数据
- (void)awakeFromNib
{
[super awakeFromNib];
self.backgroundColor = [UIColor yellowColor];
NSLog(@"%s", __func__);
}
三.利用MVC的思想对代码分组