iOS学习之自定义UItableViewCell

时间:2021-07-19 02:57:19

在项目开发中,大部分情况下我们都需要自定义UITableViewCell, 今天就重点整理一下目前自己已经学过的自定义Cell的一些注意事项;

分步骤来写吧:

1.将自定义的Cell定义为属性;

2.重写Cell独有的初始化方法;

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
//添加子控件
[self.contentView addSubview:self.avaterView]; //我们一般将自定义的View添加到Cell的contentView中;
[self.contentView addSubview:self.nameLabel];
[self.contentView addSubview:self.phoneLabel];
[self.contentView addSubview:self.callBtn];
}
return self;
}

3.重写getter方法,懒加载视图

eg:
- (UIImageView *)avaterView {
if (!_avaterView) {  //如果为空,则创建avaterView;
self.avaterView = [[[UIImageView alloc] initWithFrame:CGRectMake(, , , )] autorelease];  //不要忘了autorelease;
self.avaterView.layer.cornerRadius = ;
self.avaterView.layer.masksToBounds = YES; //将超出部分裁剪掉.
}
return [[_avaterView retain] autorelease];  //安全处理机制;
}

4.在视图控制器中调用;(当然了,别忘了import导入哦);

  4.1.在ViewDidLoad中注册自定义Cell视图

- (void)viewDidLoad {
[super viewDidLoad];
//配置导航条
[self configureNavigationBarontent]; //设置全局cell的高度
self.tableView.rowHeight = ; //注册cell
[self.tableView registerClass:[ContactCell class] forCellReuseIdentifier:@"reused"]; }

  4.2在dataSource协议方法中使用

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  //只需一步就调用完成
ContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reused" forIndexPath:indexPath];
  //对自定义的Cell进行一些简单设置
cell.avaterView.image = [UIImage imageNamed:@"Huocongcong.jpg"];
cell.nameLabel.text = @"聪聪";
cell.phoneLabel.text = @""; return cell;
}