我在我的应用程序中使用以下方法:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0)
{
cell.contentView.backgroundColor = [UIColor lightGrayColor];
cell.contentView.alpha = 0.5;
}
}
当我运行应用程序时,我的表中有7行。根据上述函数,只应格式化第一行(行号0)的单元格(因为if条件)。
第1行(行号0)的单元格格式正确(根据所需的输出)。但是,如果我向下滚动表格,则会再显示一个格式为第5行的单元格。
为什么这样?
答案 0 :(得分:4)
我认为原因是TableView重用已经存在的单元格并在可能的情况下显示它们。这里发生了什么 - 当滚动表并且第0行变得不可见时,其相应的单元用于新显示的行。因此,如果您重复使用单元格,则必须重置其属性:
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0) {
cell.contentView.backgroundColor = [UIColor lightGrayColor];
cell.contentView.alpha = 0.5; }
else
{
// reset cell background to default value
}
}
答案 1 :(得分:4)
我同意弗拉基米尔的回答。 但是,我也相信你应该采用不同的方法。
在当前情况下,您经常格式化您的单元格,因为在每个滚动条件中调用该方法,这会导致您的性能不佳。
更优雅的解决方案是将第一行格式化为与“仅一次”不同的其他格式:创建单元格时。
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier;
if(indexPath.row == 0)
CellIdentifier = @"1stRow";
else
CellIdentifier = @"OtherRows";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if(indexPath.row == 0){
cell.contentView.backgroundColor = [UIColor lightGrayColor];
cell.contentView.alpha = 0.5;
// Other cell properties:textColor,font,...
}
else{
cell.contentView.backgroundColor = [UIColor blackColor];
cell.contentView.alpha = 1;
//Other cell properties: textColor,font...
}
}
cell.textLabel.text = .....
return cell;
}