繁体   English   中英

iPhone + UITableView +格式单元格

[英]iPhone + UITableView + format cells

我在应用程序中使用以下方法:

- (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条件)。

第一行的单元格(行号0)的格式正确(根据所需的输出)。 但是,如果我向下滚动表格,则将以格式显示另外一个单元格:第5行的单元格。

为什么这样?

我认为原因是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
   }
}

我同意弗拉基米尔的回答。 但是,我也相信您应该采用不同的方法。

在当前情况下,由于每次滚动都会调用该方法,因此会频繁地格式化单元格,这会导致性能欠佳。

一个更优雅的解决方案是,在创建单元格时,将第一行的格式设置为与其他“仅一次”格式不同:

    // 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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM