封裝view較為簡(jiǎn)單二鳄,封裝tableview比較麻煩锹淌,封裝tableview的方法后面會(huì)有备图。
view的封裝
如果一個(gè)view內(nèi)部的子控件比較多,一般會(huì)考慮自定義一個(gè)view蹦肴,把它內(nèi)部子控件的創(chuàng)建屏蔽起來僚碎,不讓外界關(guān)心
外界可以傳入對(duì)應(yīng)的模型數(shù)據(jù)給view,view拿到模型數(shù)據(jù)后給內(nèi)部的子控件設(shè)置對(duì)應(yīng)的數(shù)據(jù)
-
封裝控件的基本步驟
- 在initWithFrame:方法中添加子控件(還可以使用懶加載)阴幌,提供便利構(gòu)造方法
- 在layoutSubviews方法中設(shè)置子控件的frame
//一定要調(diào)用 [super layoutSubviews];
- 增加模型屬性勺阐,在模型數(shù)據(jù)set方法中設(shè)置數(shù)據(jù)到子控件上
+ (instancetype)shopView
{
return [[self alloc] init];
}
- (UIImageView *)iconView
{
if (_iconView == nil) {
UIImageView *iconView = [[UIImageView alloc] init];
iconView.backgroundColor = [UIColor blueColor];
[self addSubview:iconView];
_iconView = iconView;
}
return _iconView;
}
- (UILabel *)nameLabel
{
if (_nameLabel == nil) {
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.font = [UIFont systemFontOfSize:11];
nameLabel.textAlignment = NSTextAlignmentCenter;
nameLabel.backgroundColor = [UIColor redColor];
[self addSubview:nameLabel];
_nameLabel = nameLabel;
}
return _nameLabel;
}
/**
init方法內(nèi)部會(huì)自動(dòng)調(diào)用initWithFrame:方法
*/
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
}
return self;
}
/**
* 這個(gè)方法專門用來布局子控件,一般在這里設(shè)置子控件的frame
* 當(dāng)控件本身的尺寸發(fā)生改變的時(shí)候矛双,系統(tǒng)會(huì)自動(dòng)調(diào)用這個(gè)方
*
*/
- (void)layoutSubviews{
// 一定要調(diào)用super的layoutSubviews
[super layoutSubviews];
}
- (void)setShop:(YWShop *)shop
{
}