- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [superinitWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
[self createUI];
}
returnself;
}
这里我们给UI页面的定制,单独写成一个方法,然后去进行我们自己的定制
- (void)createUI{
_iconView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 70, 70)];
[self.contentView addSubview:_iconView];
_nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, 5, 230, 25)];
_nameLabel.font = [UIFont systemFontOfSize:16];
_nameLabel.textColor = [UIColor blackColor];
[self.contentView addSubview:_nameLabel];
_priceLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, 30, 230, 25)];
_priceLabel.font = [UIFont systemFontOfSize:14];
_priceLabel.textColor = [UIColor redColor];
[self.contentView addSubview:_priceLabel];
_detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, 55, 230, 25)];
_detailLabel.font = [UIFont systemFontOfSize:12];
_detailLabel.textColor = [UIColor grayColor];
[self.contentView addSubview:_detailLabel];
}
可以看到,我们在当前的cell上,自定义了一个UIImageView用来加载图片,三个UILable用来展示相应的信息。一般来说,Controller里面采用的是self.view addSubview的方式来加载控件,同样的,UITableViewCell也是一个View,但是它就不能用view ,而是用contentView来加载,这个以后再提。于是这样我们就能将我们需要的设计,在我们这个cell里实现了。
在日常的开发工作中,很少有将数据写死的,通常都是从后台通过请求接受数据,然后将数据再根据需要加载到相应的控件上,所以对于我们来说,控件是可变的,控件上的数据是可变的,这样的话,我们就将所需要的数据单独抽取出来建成一个模型。分析一下需求与代码,我们现在需要的是一个UIImageView的image与三个UILable的text信息,所以,我们将这些属性单独抽取出来作为我们这个cell的模型。
新建一个MyModel类,这个类继承自NSObject,里面放的就是我们cell的属性,代码如下:
@property (retain, nonatomic) UIImage *icon;
@property (copy, nonatomic) NSString *nameStr;
@property (copy, nonatomic) NSString *priceStr;
@property (copy, nonatomic) NSString *detailStr;
注意:因为我们这个类是需要让其他的类引用,并且是需要接受数据的,所以应该写在.h文件,interface下面。
到这里,我们的MVC的思想大致就出来了,但是还有一个问题,那就是如何让cell与自己的