-
為什么要封裝view
-
如果一個(gè)view內(nèi)部的子控件比較多蒙挑,一般會(huì)考慮自定義一個(gè)view宗侦,把它內(nèi)部子控件的創(chuàng)建屏蔽起來(lái),不讓外界關(guān)心
-
外接可以傳入對(duì)應(yīng)的模型數(shù)據(jù)給view忆蚀,view拿到模型數(shù)據(jù)后給內(nèi)部的子控件設(shè)置對(duì)應(yīng)的數(shù)據(jù)
-
-
封裝控件的基本步驟
-
新建一個(gè)類(lèi)繼承自
UIView
-
在initWithFrame:方法中添加子控件矾利,提供遍歷構(gòu)造方法
-
/**
初始化
@param frame
-
@return WXShopView
*/
-(instancetype)initWithFrame:(CGRect)frame
{
if(self = [super initWithFrame:frame])
{// self.backgroundColor = [UIColor orangeColor]; // 添加圖片 UIImageView *iconView = [[UIImageView alloc] init]; iconView.backgroundColor = [UIColor blueColor]; [self addSubview:iconView]; self.iconView = iconView; // 添加文字 UILabel *label = [[UILabel alloc] init]; label.backgroundColor = [UIColor redColor]; label.font = [UIFont systemFontOfSize:11]; label.textAlignment = NSTextAlignmentCenter; [self addSubview:label]; self.nameLabel = label;
}
return self;
}
- #####在layoutSubviews方法中設(shè)置子控件的frame(一定要調(diào)用super的layoutSubviews)
```objc
/**
* 控件大小改變事件
*/
-(void)layoutSubviews
{
[super layoutSubviews];
float shopW = self.frame.size.width;
float shopH = self.frame.size.height;
self.iconView.frame = CGRectMake(0, 0, shopW, shopW);
self.nameLabel.frame = CGRectMake(0, shopW, shopW, shopH - shopW);
}
-
增加模型屬性,在模型屬性的set方法中設(shè)置數(shù)據(jù)到子控件
/**
* Shop的set方法
*
* @param shop
*/
-(void)setShop:(Shop *)shop
{
_shop = shop;
self.iconView.image = [UIImage imageNamed:shop.icon];
self.nameLabel.text = shop.name;
}
-
注意點(diǎn)
- 使用initWithFrame初始化方法馋袜,因?yàn)樵谡{(diào)用init方法之后系統(tǒng)會(huì)再調(diào)用initWithFrame方法