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