项目上经常需要定制tableView的cell,比如今天会想在cell上另外添加label记录此cell所在的行数,因为cell的重用机制是系统已经设置好了的,可以按以下方式进行:
static NSString *CellIdentifier = @"tableViewCellReuseID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.accessoryType = UITableViewCellAccessoryNone;
/*
CGRect cellFrame = cell.frame;
CGRect labelFrame = CGRectMake(cellFrame.size.width - 25, cellFrame.origin.y, 20, cellFrame.size.height);
_countLabel = [[UILabel alloc] initWithFrame:labelFrame];
CGPoint tmpCenter = _countLabel.center;
tmpCenter.y = cell.bounds.size.height / 2;
_countLabel.center = tmpCenter;
[cell addSubview:_countLabel];
}
但是新添加的label不能像上面红色字体显示的代码那样直接在这个 if 语句里alloc,然后直接在外面使用,那样的话每次就只会重用最后定义的label,所显示的数目肯定会有问题。
这个时候我们可以使用label的tag属性。只需简单的在上述红色语句里添加:
_countLabel.tag = 101;
再在 if 语句外面按以下方式提取出来:
_countLabel = (UILabel*)[cell viewWithTag:101];
static NSString *CellIdentifier = @"Cell";
BOOL nibsRegistered = NO;
if (!nibsRegistered) {
UINib *nib = [UINib nibWithNibName:NSStringFromClass([Cell class]) bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
nibsRegistered = YES;
}
Cell *cell = (Cell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.titleLabel.text = [self.dataList objectAtIndex:indexPath.row];
return cell;