2009-11-27 180 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 
    } 
}