tableviewcell在加载的过程中常常需要重用,主要在使用的是两种加载的方法。第一种是在storyboard中直接加载,这种方法不需要进行初始化,可以直接使用。但是要注意identifier一定要设置,控制器是根据identifier来识别cell的。
第二种方法是用xib文件来加载,同样要设置identifier。不过多了从文件中读取xib的过程。代码如下:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{MyCustomCell * cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
if (!cell)
{
[tableView registerNib:[UINib nibWithNibName:@"MyCustomCell" bundle:nil] forCellReuseIdentifier:@"myCell"];
cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
}
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(MyCustomCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.leftLabel.text = [self.items objectAtIndex:indexPath.row];
cell.rightLabel.text = [self.items objectAtIndex:indexPath.row];
cell.middleLabel.text = [self.items objectAtIndex:indexPath.row];
}