2014-10-03 107 views
0

我有一個可用視圖,其中包含人員列表。有些記錄有圖像,有些記錄沒有。如果我向下滾動列表,它看起來是正確的,但如果我向後滾動,那麼另一個人的圖像開始顯示在其他人的細胞行上,圖像不應該是。這是我的代碼cellForRowAtIndexPathUITableView imageView顯示圖像滾動後圖像不應該在哪裏

// START CELL LABELLING FOR TABLE VIEW LIST // 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 


    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if(!cell){ 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 


    Person *person = [arrayOfPersons objectAtIndex:indexPath.row]; 



    NSString *personPhoto = person.personPhoto; 

    NSString* imgPath = [docPath stringByAppendingPathComponent: 
         [NSString stringWithFormat:@"%@", personPhoto] ]; 



    if ([[NSFileManager defaultManager] fileExistsAtPath:imgPath]){ 
     NSLog(@"FILE EXISTS"); 

    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(240, 0, 67, 67)]; 
    imageView.image = [UIImage imageWithContentsOfFile:imgPath]; 
    imageView.contentMode = UIViewContentModeScaleAspectFit; 
    [cell.contentView addSubview:imageView]; 
    }else{ 
     NSLog(@"Does Not Exist"); 
    } 


    cell.textLabel.text = person.personName; 



    return cell; 
    imageView = nil; 
    personPhoto = @""; 
    imgPath = @""; 
} 
// END CELL LABELLING FOR TABLE VIEW LIST // 
+0

可能你需要做[cell.contentView.view removeFromSuperview];之前添加一個新的地方。 – kabarga 2014-10-03 12:22:55

回答

0

這種情況發生的原因是因爲表格單元格被重新使用。

當您使用[tableView dequeueReusableCellWithIdentifier:CellIdentifier]時,您將獲取已在表格視圖中顯示的單元格(對於不同的索引路徑)。您可能已經在此單元格中爲此人以前的索引路徑添加了圖像視圖,並且無處刪除此圖像。

因此,當前Person沒有照片時,先前的圖像將在單元格中保持可見。

我建議創建自己的UITableViewCell子類,並在其中添加UIImageView,以便您可以輕鬆地獲取圖像視圖的引用(或者如果您願意,可以使用視圖標記)。

無論哪種方式,當人沒有照片時,您需要刪除圖像視圖/將圖像設置爲nil

+0

你能指點我創建我自己的UITableViewCell – user520300 2014-10-03 14:24:58

+0

正確的方向你可以創建一個'UITableViewCell'子類('File> New> File')。然後,您可以根據需要設置佈局(使用代碼或使用界面生成器)。您可以爲照片的圖像視圖添加一個公共插座,然後您可以在您的'tableView:cellForRowAtIndexPath:'方法中設置圖像(以及其他可能需要的東西(標籤等))。我希望這是有道理的 :) – JoeFryer 2014-10-03 15:59:56