2009-11-27 267 views
1

我使用下面的方法在我的应用程序:iPhone +的UITableView +格式细胞

- (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的单元格。

为什么这样?

回答

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