view的封装
- 如果一个view内部的子空间比较多,一般会考虑自定义一个view,把它内部子控件的创建屏蔽起来,不让外界关心
- 外界可以传入对应的数据模型给view,view拿到模型数据后给内部的子控件设置对应的数据
封装控件的基本步骤
- 第一步:在initWithFrame:方法中添加子控件,提供便利构造
- 调用init方法,会自动调用initWithFrame:方法
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super init]) {
_imageView = [[UIImageView alloc]init];
[_imageView setBackgroundColor:[UIColor redColor]];
[self addSubview:_imageView];
_label = [[UILabel alloc]init];
[_label setBackgroundColor:[UIColor blueColor]];
[self addSubview:_label];
}
return self;
}
- 第二步:在layoutSubviews方法中设置子控件的frame(一定要调用super的layoutSubviews)
- (void)layoutSubviews
{
[super layoutSubviews];
CGFloat viewW = self.frame.size.width;
CGFloat viewH = self.frame.size.height;
_imageView.frame = CGRectMake(0, 0, viewW, viewW);
_label.frame = CGRectMake(0, viewW, viewW, viewH - viewW);
}
- 第三步:增加模型属性,在模型属性set方法中设置数据到子控件
/** 模型数据接口*/
@property (nonatomic, strong) WQShopData *shopData;
- (void)setShopData:(WQShopData *)shopData
{
[self.imageView setImage:[UIImage imageNamed:shopData.icon]];
self.label.text = shopData.name;
}
WQShopView *view = [[WQShopView alloc]init];
view.frame = CGRectMake(originalX + (marginX + kImageViewW) * col, originalY + (kImageViewH + kMarginY) *row, kImageViewW, kImageViewH);
view.shopData = self.shopsData[index];
[self.shopsView addSubview:view];
- 当view内部子控件很多,可以封装起来.当在外部创建该view对象,并设置或者修改该控件的frame时,就会自动调用layoutSubviews,这时可以设置修改子控件的frame(这时子控件才会显示,还没数据).
- 在传入模型数据时,会调用数据模型的setter方法,这时设置子控件的数据(子控件显示数据)
- 优化:有些子控件,开始不显示,需要时才显示,这时可以通过懒加载方式,在使用子控件时会调用其getter方法,在里面加载并只加载一次子控件.
#import "WQShopView.h"
#import "WQShopData.h"
@interface WQShopView ()
/**图片*/
@property (nonatomic, strong) UIImageView * imageView;
/**名字*/
@property (nonatomic, strong) UILabel * label;
@end
@implementation WQShopView
- (UIImageView *)imageView
{
if (_imageView == nil) {
_imageView = [[UIImageView alloc]init];
[_imageView setBackgroundColor:[UIColor redColor]];
[self addSubview:_imageView];
}
return _imageView;
}
- (UILabel *)label
{
if (_label == nil) {
_label = [[UILabel alloc]init];
[_label setBackgroundColor:[UIColor blueColor]];
[self addSubview:_label];
}
return _label;
}