2010-06-22 81 views
0

我添加了一个子视图uitableviewcells其工作正常,但是当我向上或向下滚动子视图添加多次。我不知道我错在哪里。uitableviewcell的子视图问题

这里是我的代码:

- (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

您要添加子视图他们是否刚刚创建或他们正在重用的细胞。当您上下滚动时,它们会被重用,因此子视图会重复添加。

将调用移动到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]; 
} 
+0

谢谢你......它工作正常..... – mano 2010-06-22 21:49:05

+0

太好了。请接受答案,并确认它是否正确。 – 2010-06-22 22:14:43