iOS边练边学--view的封装

一、view封装的思路:

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

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

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

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

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

1 @interface ChaosShopView () // 类扩展,定义子控件成员变量,保证封装性
2 /** 商品图片 */
3 @property(nonatomic,strong) UIImageView *thingImg;
4 /** 商品名称 */
5 @property(nonatomic,strong) UILabel *thingLabel;
6 
7 @end
 1 // 步骤一:重写构造方法,定义需要的子控件 init方法内部会自动调用initWithFrame:方法
 2 - (instancetype)initWithFrame:(CGRect)frame
 3 {
 4     if (self = [super initWithFrame:frame]) {
 5         self.backgroundColor = [UIColor redColor];
 6         // 创建图片
 7         UIImageView *image = [[UIImageView alloc] init];
 8         image.backgroundColor = [UIColor blueColor];
 9         _thingImg = image;
10         
11         // 创建标签
12         UILabel *label = [[UILabel alloc] init];
13         label.backgroundColor = [UIColor orangeColor];
14         label.textAlignment = NSTextAlignmentCenter;
15         label.font = [UIFont systemFontOfSize:13];
16         _thingLabel = label;
17         
18         [self addSubview:label];
19         [self addSubview:image];
20 
21     }
22     return self;
23 }

  2>设置子控件的尺寸

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

 1 // 步骤二:重写layoutSubviews方法,父控件尺寸改变时调用该方法。父控件有了尺寸再设置子控件的尺寸
 2 // 注意的是:一定调用父类的layoutSubviews方法
 3 - (void)layoutSubviews
 4 {
 5     // 一定调用父类的方法
 6     [super layoutSubviews];
 7     // 一般在这个方法里设置子控件的尺寸
 8     CGFloat width = self.frame.size.width;
 9     CGFloat height = self.frame.size.height;
10     self.thingImg.frame = CGRectMake(0, 0, width, width);
11     self.thingLabel.frame = CGRectMake(0, width, width, height - width);
12 }

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

 1 #import <UIKit/UIKit.h>
 2 #import "ShopModel.h"
 3 
 4 @interface ChaosShopView : UIView
 5 
 6 /** 数据模型 */
 7 @property(nonatomic,strong) ShopModel *shopModel;
 8 
 9 // 定义一个类方法
10 + (instancetype)shopView;
11 
12 @end
1 // 步骤三:定义模型成员变量,重写模型的set方法,为子控件加载数据
2 -(void)setShopModel:(ShopModel *)shopModel
3 {
4     // 先给成员变量赋值,把值存起来
5     _shopModel = shopModel;
6     [self.thingImg setImage:[UIImage imageNamed:shopModel.icon]];
7     self.thingLabel.text = shopModel.name;
8 }

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

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

+(instancetype)shopView
{
    return [[ChaosShopView alloc] init]; // init方法中会调用自己重写的initWithFrame:方法
}

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

1     // 类方法快捷创建
2     ChaosShopView *shopView = [ChaosShopView shopView];
3     // 设置尺寸
4     shopView.frame = CGRectMake(bagX, bagY, bagWidth, bagHeight);
5     // 数据
6     shopView.shopModel = shopModel;
原文地址:https://www.cnblogs.com/gchlcc/p/5246648.html