标签:
在 .h 文件中声明模型对象 @class@property(nonatomic,strong)Shop *shop;
目的:封装控件内部的细节,不让外界关心
添加子控件
initWithFrame
方法initWithFrame
方法建议在此设置必要的Frame
-(instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
UIImageView *shopImage = [[UIImageView alloc] init];
[self addSubview:shopImage];
_shopImage = shopImage;
UILabel *shopLabel = [[UILabel alloc] init];
[self addSubview:shopLabel];
_shopLabel = shopLabel;
}
return self;
}
- 在layoutSubviews方法中设置子控件的frame
- 一定要调用[super layoutSubviews];
/**
* 当前控件的frame发生改变的时候就会调用
* 第一次显示也会调用
* 这个方法专门用来布局子控件,设置子控件的frame
*/
- (void)layoutSubviews
{
// 一定要调用super方法
[super layoutSubviews];
CGFloat shopW = self.frame.size.width;
CGFloat shopH = self.frame.size.height;
self.shopImage.frame = CGRectMake(0, 0, shopW, shopW);
self.shopLabel.frame = CGRectMake(0, shopW, shopW, shopH - shopW);
}
- 提供一个模型属性,重写模型属性的set方法
- 在set方法中取出模型属性,给对应的子控件赋值
//重写set方法
- (void)setShop:(Shop *)shop
{
_shop = shop;
self.shopImage.image = [UIImage imageNamed:shop.icon];
self.shopLabel.text = shop.namelabel;
}
+(instancetype)photoViewWithPhoto:(Photo *)photo
{
SYLView *sylView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];
sylView.photo = photo;
return sylView;
}
//重写set方法
- (void)setPhoto:(Photo *)photo
{
_photo = photo;
_photoShow.image = [UIImage imageNamed:photo.photoName];
_pledge.text = photo.pledge;
}
xib 编译之后变为 Nib 文件
第一种加载方法
//返回一个数组
NSArry *xibArray = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil];
/*
* 参数 NSString * 是 xib 文件名
* NSBundle * 传入 mainBundle
* 如果传入参数是 mainBundle 则可以传入 nil
*
*/
UINib *nib = [UINib nibWithNibName:<#(NSString *)#> bundle:<#(NSBundle *)#>]
标签:
原文地址:http://www.cnblogs.com/ShaoYinling/p/4603308.html