-
以創(chuàng)建一個顯示一張照片的cell為例,效果如下:
屏幕快照 2016-10-17 下午12.25.24.png 第一步:創(chuàng)建一個類繼承自UITableViewCell,把要顯示的控件添加為這個類的成員屬性
#import <UIKit/UIKit.h>
@interface LCHShopRecommendCell : UITableViewCell
//cell要顯示的圖片
@property(nonatomic,strong)UIImageView *shopV;
//創(chuàng)建cell的方法
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end
- 第二步:實現(xiàn)cellWithTableView(這一步主要是為簡化創(chuàng)建cell的方法,可寫可不寫,不寫的話創(chuàng)建cell的方式會有所不同)
+(instancetype)cellWithTableView:(UITableView *)tableView
{
static NSString *identifier = @"cell";
//從緩存池中找
LCHShopRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//設置背景色
[cell setBackgroundColor:[UIColor clearColor]];
if (cell == nil) {
cell = [[LCHShopRecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
return cell;
}
- 第三步:重寫initWithStyle:在初始化對象的時候會調用,一般在這個方法中添加要顯示的子控件
/**
* 構造方法(在初始化對象的時候會調用)
* 一般在這個方法中添加要顯示的子控件
*/
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
//讓自定義cell和系統(tǒng)的cell一樣,一創(chuàng)建出來就有一些子控件給我們使用
//創(chuàng)建商品推薦圖
self.shopV = [UIImageView new];
[self.contentView addSubview:_shopV];
}
return self;
}
- 第四步:重寫layoutSubviews:一般在這個方法設置cell里邊控件的frame
/**
* 設置子控件的frame
*/
-(void)layoutSubviews
{
// self.shopV.frame = CGRectMake(10, 5, self.frame.size.width-20, self.frame.size.height-20);
//用masonary框架布局控件
[self.shopV mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(7);
make.left.mas_equalTo(7);
make.right.mas_equalTo(-7);
make.bottom.mas_equalTo(0);
}];
}
- 到了第四步,純代碼自定義cell的工作就完成了,且記使用的時候的是要先在控制器注冊cell
//viewDidLoad中注冊cell
[self.lchHomev.recommendTableV registerClass:[LCHShopRecommendCell class]forCellReuseIdentifier:@"cell"];
//創(chuàng)建cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//有實現(xiàn)cellWithTableView:方法,創(chuàng)建cell可以一句代碼搞定
LCHShopRecommendCell *cell = [LCHShopRecommendCell cellWithTableView:tableView];
//設置圖片
LCHRecommendShopModel *model = _recommendPics[indexPath.row];
[cell.shopV sd_setImageWithURL:[NSURL URLWithString:model.recommenImage]];
}
return cell;
}
