2014-10-20 42 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