2014-10-20 43 views
0

我有一個允許多個選擇的UITableView,但由於某種原因,當我滾動UITableView時,我用UITableViewCellAccessoryCheckmark作出的選擇重複,因爲我滾動。UITableViewCell accessoryType UITableViewCellAccessoryCheckmark重複

這是我使用

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    cell.backgroundColor = [UIColor clearColor]; 

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

    // Configure the cell... 
    cell.textLabel.text = [sortedMachineNames objectAtIndex:indexPath.row]; 

    return cell; 
} 

#pragma mark - Table view delegate 

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath: 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    [selectedMachinesMArray addObject:cell.textLabel.text]; 
} 

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

    cell.accessoryType = UITableViewCellAccessoryNone; 
    NSUInteger index = [selectedMachinesMArray indexOfObject:cell.textLabel.text]; 
    if (index!=NSNotFound) { 
     [selectedMachinesMArray removeObjectAtIndex:index]; 
    } 
} 

任何幫助,將不勝感激的代碼。

+0

「但是出於某種原因......」的原因是小區重用。搜索「複選標記重複」,你會發現很多答案。 – rdelmar 2014-10-20 20:50:38

回答

2

在cellforIndexAtPath做電池的當前狀態的檢查和更改accesory類型的值,就像這樣:

if(marked) 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
else 
    cell.accessoryType = UITableViewCellAccessoryNone; 
+0

標記的最佳做法是什麼?我應該爲UITableView中的每個UITableViewCell創建一個完全獨立的T/F數組? – HurkNburkS 2014-10-20 21:52:39

+1

OKay我剛剛做了這個,創建了一個數組,其長度與UITableView相同,將數組中的每個值都設置爲false,然後當存在選擇或取消選擇時,我將數組中的值設置爲true或false。 – HurkNburkS 2014-10-20 22:18:35

+1

@HurkNburkS這是正確的,我在開始時遇到了這個問題,對於圖形方面你可以使用「WillDisplayCell:forRowAtIndexPath」P.D,如果你發現我的答案有用,你可以upvoteme? – Darklex 2014-10-20 22:54:02