2010-06-22 87 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