iOS边练边学--view的封装

一、view封装的思路:

*如果一个view内部的子控件比较多,一般会考虑自定义一个view,把它内部的子控件的创建屏蔽起来,不让外界关心

*外界可以传入对应的模型数据给view,view拿到模型数据后给内部的子控件设置对应的数据


二、封装控件的基本步骤--四步

1>添加子控件(子控件也可通过懒加载实现)

*在initWithFrame:方法中添加子控件,提供便利构造方法  ps--init方法内部会调用initWithFrame:方法,所以说外部调用的时候直接用init调用

@interface ChaosShopView () // 类扩展,定义子控件成员变量,保证封装性

/** 商品图片 */

@property(nonatomic,strong) UIImageView *thingImg;

/** 商品名称 */

@property(nonatomic,strong) UILabel *thingLabel;

@end

// 步骤一:重写构造方法,定义需要的子控件 init方法内部会自动调用initWithFrame:方法

- (instancetype)initWithFrame:(CGRect)frame

{

if (self = [super initWithFrame:frame]) {

self.backgroundColor = [UIColor redColor];

// 创建图片

UIImageView *image = [[UIImageView alloc] init];

image.backgroundColor = [UIColor blueColor];

_thingImg = image;

// 创建标签

UILabel *label = [[UILabel alloc] init];

label.backgroundColor = [UIColor orangeColor];

label.textAlignment = NSTextAlignmentCenter;

label.font = [UIFont systemFontOfSize:13];

_thingLabel = label;

[self addSubview:label];

[self addSubview:image];

}

return self;

}

2>设置子控件的尺寸

*在layoutSubviews方法中设置子控件的frame(一定要调用super的layoutSubviews)。不在构造方法中设置子控件尺寸的原因是:子控件的尺寸可能会用到父类的尺寸,在构造函数中父类的frame属性不一定有值,从而导致子控件的frame属性值也会为0。layoutSubviews方法的触发是当父类控件的frame属性发生改变的时候触发!

// 步骤二:重写layoutSubviews方法,父控件尺寸改变时调用该方法。父控件有了尺寸再设置子控件的尺寸

// 注意的是:一定调用父类的layoutSubviews方法

- (void)layoutSubviews

{

// 一定调用父类的方法

[super layoutSubviews];

// 一般在这个方法里设置子控件的尺寸

CGFloat width = self.frame.size.width;

CGFloat height = self.frame.size.height;

self.thingImg.frame = CGRectMake(0, 0, width, width);

self.thingLabel.frame = CGRectMake(0, width, width, height - width);

}

3>增加模型属性(这个不要定义在扩展类中了,因为外界需要访问传数据),在模型属性set方法中设置数据到子控件上。

#import#import "ShopModel.h"

@interface ChaosShopView : UIView

/** 数据模型 */

@property(nonatomic,strong) ShopModel *shopModel;

// 定义一个类方法

+ (instancetype)shopView;

@end

// 步骤三:定义模型成员变量,重写模型的set方法,为子控件加载数据

-(void)setShopModel:(ShopModel *)shopModel

{

// 先给成员变量赋值,把值存起来

_shopModel = shopModel;

[self.thingImg setImage:[UIImage imageNamed:shopModel.icon]];

self.thingLabel.text = shopModel.name;

}

4>可以增加一个类方法,实现快捷开发

声明的代码就不写了,直接写实现的代码吧

+(instancetype)shopView

{return[[ChaosShopView alloc] init]; // init方法中会调用自己重写的initWithFrame:方法

}

三、创建控件的时候几行代码就搞定

// 类方法快捷创建

ChaosShopView *shopView = [ChaosShopView shopView];

// 设置尺寸

shopView.frame = CGRectMake(bagX, bagY, bagWidth, bagHeight);

// 数据

shopView.shopModel = shopModel;

你可能感兴趣的:(iOS边练边学--view的封装)