uitableviewcell子视图的问题

时间:2010-06-22 21:28:03

标签: iphone

我向uitableviewcells添加了一个子视图,它的工作正常,但是当我向上或向下滚动时,子视图会多次添加。我不知道我错了。

这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 static NSString *CellIdentifier = @"MainPageCellView";
 MainPageTableCellView *cell = (MainPageTableCellView *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

 if (cell == nil) {  
  [[NSBundle mainBundle] loadNibNamed:@"MainPageTableCellView" owner:self options:nil];  
  cell = mainPageTableCell;
 } 



 [cell setNameText:[namesArray objectAtIndex:indexPath.row]];
 [cell setPositionText:[positionArray objectAtIndex:indexPath.row]];
 [cell setCompanyNameText:[companyNameArray objectAtIndex:indexPath.row]];
 [cell setDistanceText:[distArray objectAtIndex:indexPath.row]];
 [cell setImageViewImage:[imagesArray objectAtIndex:indexPath.row]];


 UIImage *halo = [UIImage imageNamed:@"h1.png"]; 
 UIImageView *haloV = [[UIImageView alloc] initWithImage:halo];

 if(indexPath.row == 0)
 [cell addSubview: haloV];
 else if(indexPath.row ==2)
 [cell addSubview: haloV];
 else if(indexPath.row ==3)
 [cell addSubview: haloV];


 return cell;

}

1 个答案:

答案 0 :(得分:1)

您正在向细胞添加子视图,无论它们是刚刚创建还是正在重复使用。当您向上和向下滚动时,它们会被重复使用,因此会重复添加子视图。

将调用移到if(cell == nil)块中的addSubview,这样可以解决问题。

 if (cell == nil) {  
   [[NSBundle mainBundle] loadNibNamed:@"MainPageTableCellView" owner:self options:nil];  
   cell = mainPageTableCell;

   UIImage *halo = [UIImage imageNamed:@"h1.png"]; 
   UIImageView *haloV = [[UIImageView alloc] initWithImage:halo];

   if(indexPath.row == 0)
     [cell addSubview: haloV];
   else if(indexPath.row ==2)
     [cell addSubview: haloV];
   else if(indexPath.row ==3)
     [cell addSubview: haloV];
 }