前提:
1.如果一个View内部的子控件比较多,比如“一线销售助手”图片上传的图片排布。一般会考虑自定义一个view,把它内部的子空间的创建屏蔽起来,不让外界关心。
2.外界可以传入对应的数据模型提供给View,view拿到模型数据之后给内部的子控件设置对应的数据
步骤:
1.在initWithFrame:方法中添加控件(注意init方法会自动调用initWithFrame:方法,所以最好用withFram来添加)
添加控件时也可以 用懒加载的方式加载控件
/** 采用懒加载来添加控件*/ -(UILabel *)nameLabel{ if (!_nameLabel) { _nameLabel = [[UILabel alloc]init]; _nameLabel.backgroundColor = [UIColor redColor]; [self addSubview:_nameLabel]; } return _nameLabel; } -(UIImageView *)iconView{ if (!_iconView) { _iconView = [[UIImageView alloc]init]; _iconView.backgroundColor = [UIColor greenColor]; [self addSubview:_iconView]; } return _iconView; }
// 类方法 +(instancetype)shopView{ return [[self alloc]init]; } // 构造方法 /** *init方法会自动调用initWithFrame:方法 */ -(instancetype)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) { self.backgroundColor = [UIColor orangeColor]; _iconView = [[UIImageView alloc]init]; _iconView.backgroundColor = [UIColor greenColor]; [self addSubview:_iconView]; _nameLabel = [[UILabel alloc]init]; _nameLabel.backgroundColor = [UIColor redColor]; [self addSubview:_nameLabel]; } return self; }
2.在layoutSubviews方法中设置子控件的fram(一定要先写上[super layoutSubviews];)
/** *这个方法专门用来布局子控件,一般在这里设置子控件的fram *当控件本身的尺寸发生改变的时候,系统会自动调用这个方法 * */ -(void)layoutSubviews{ // 一定要调用super的layoutSubviews [super layoutSubviews]; CGFloat W = self.frame.size.width; CGFloat H = self.frame.size.height; _iconView.frame = CGRectMake(0, 0, W, W); _nameLabel.frame = CGRectMake(0, W, W, H-W); }
3.增加模型属性,在模型属性的set方法中设置数据到子控件上(如果传入的是数组,也是同样的道理)
-(void)setShop:(DCYShops *)shop{ _shop = shop; // 设置图片的内容和label的内容 _nameLabel.text = _shop.name; _iconView.image = [UIImage imageNamed:_shop.icon]; }
知识点:
1.在一个View中调用一个model类,作为view的一个属性时,在.h中用@class,然后在.m中再#import ""
2.self.和下划线定义的变量的区别:self.是间接的调用了get方法和set方法。而_XX只是获取自己的实例变量,不包含set和get的方法。所以在懒加载中要注意判断if()括号里面时不要使用self.而应该使用下划线
知识的补充:
封装控件的时候,考虑到如果是需要xib,拖控件的形式来创建你自定义的空件,如果用initWithFrame:的方法,其初始化是不成功的,因为xib是通过initWithCoder:这个方法,并且为了防止在控件还没有完全成型的时候,被调用,其初始化最好在awakeFromNib这个方法时候,而initWithCoder:可以不写
/** xib创建拥有中划线的控件*/ - (void)awakeFromNib { [self setup]; } // 初始化控件的字体颜色,字体居中 - (void)setup { self.textColor = [UIColor blackColor]; self.backgroundColor = [UIColor greenColor]; self.textAlignment = NSTextAlignmentCenter; }