2013-06-20 62 views
0

我的UITableView正在從數組中提取數據。此數組中的項目有一個名爲IsSelected的屬性。我正在嘗試將UIImageView放入單元格contentView中,用於選擇每個項目。UIImageView添加到單元格contentView在滾動UITableView時隨機顯示

然而,當重複使用單元格時,UITableView會導致我的圖像在不應該使用的單元格上重用。我無法弄清楚我的生活,我應該如何改變它。我附上了一個顯示問題的屏幕快照。如果我繼續和滾動上下圖像去所有的地方:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *SchoolCellIdentifer = @"SchoolCellIdentifier"; 

    SchoolInfoItem *item = [self.schoolsArray objectAtIndex:indexPath.row]; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SchoolCellIdentifer]; 

    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SchoolCellIdentifer]; 
     cell.contentView.backgroundColor = [BVColors WebDarkBlue]; 
    } 

    cell.textLabel.text = item.Name; 

    if ([item.selected isEqualToString:@"1"]) 
    { 
     cell.contentView.backgroundColor = [BVColors WebBlue]; 
     UIImageView *selectedItemCheckMarkIcon = [[UIImageView alloc] initWithFrame:CGRectMake(300, 13, 17, 17.5)]; 
     [selectedItemCheckMarkIcon setImage:[UIImage imageNamed:@"check-mark.png"]]; 
     [cell.contentView addSubview:selectedItemCheckMarkIcon]; 
    } 
    else 
    { 
     cell.contentView.backgroundColor = [BVColors WebDarkBlue]; 
    } 

    return cell; 
} 

enter image description here

回答

1

你需要確保UIImageView正從單元格內容視圖中刪除。它看起來像在你的代碼中,當一個單元格出現時,imageview仍然在單元格視圖層次結構中。

最好的解決方案是讓您的單元格保留對圖像視圖的引用,並在必要時將其刪除。

採取以下:

if ([item.selected isEqualToString:@"1"]) 
{ 
    cell.contentView.backgroundColor = [BVColors WebBlue]; 
    cell.myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(300, 13, 17, 17.5)]; 
    [selectedItemCheckMarkIcon setImage:[UIImage imageNamed:@"check-mark.png"]]; 
    [cell.contentView addSubview:cell.myImageView]; 
} 
else 
{ 
    [cell.myImageView removeFromSuperview]; 
    cell.myImageView = nil; 
    cell.contentView.backgroundColor = [BVColors WebDarkBlue]; 
} 

注意在其他情況下,去除的ImageView的。

+0

謝謝你做到了! – Flea

+0

非常歡迎:) –

1

您不斷添加UIImageView作爲單元格contentView的子視圖。當表格視圖重新使用單元格時,這不會被刪除。如果它不應該出現,你需要刪除子視圖。

你應該在UITableViewCell子類別上製作selectedItemCheckMarkIcon屬性。然後在你的子類中設置一個方法,在其中設置圖像或圖像的可見性。

你也可以使用上的UITableView的accessoryView屬性和設置的ImageView爲:

if ([item.selected isEqualToString:@"1"]) { 
    cell.contentView.backgroundColor = [BVColors WebBlue]; 
    UIImageView *selectedItemCheckMarkIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"check-mark.png"]]; 
    cell.accessoryView = selectedItemCheckMarkIcon; 
} else { 
    cell.accessoryView = nil; 
    cell.contentView.backgroundColor = [BVColors WebDarkBlue]; 
} 

請注意,您不需要設置在這種情況下,一個幀,因爲系統會自動設置幀正確爲accessoryView

+0

謝謝runmad!感謝您的反饋。我標記丹是答案,因爲他先回答,但我標記你的幫助!再次感謝! – Flea

+0

不用擔心。儘管如此,我建議您使用'accessoryView',因爲如果您需要的只是一個複選標記,它可以更容易地管理:)附帶適當的框架,並且在您不需要它的單元格中很容易刪除。 – runmad

相關問題