2011-12-31 128 views
0

我需要在我的tableview中启用多项选择,并且还需要跟踪我选择的内容(如将其保存到数组或其他内容中)。我迄今的做法;从表中选择多条记录

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

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

    cell.textLabel.text=[arrayobject objectAtIndex:indexPath.row]; 

    bool xx = [[allmyselectedobjects objectAtIndex:indexPath.row] containsIndex:1]; 

     if (xx) { 
      [cell setAccessoryType:UITableViewCellAccessoryCheckmark]; 
     }else{ 
      [cell setAccessoryType:UITableViewCellAccessoryNone]; 
     } 

    return cell; 
} 

和didSelectRowAtIndexPath方法方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [self.cuisineTableView cellForRowAtIndexPath:indexPath]; 
    if ([cell accessoryType] == UITableViewCellAccessoryNone) { 
     [cell setAccessoryType:UITableViewCellAccessoryCheckmark]; 
     [self.allmyselectedobjects insertObject:1 atIndex:indexPath.row];   
    } 
    else { 
     [cell setAccessoryType:UITableViewCellAccessoryNone]; 
     [self.allmyselectedobjects insertObject:0 atIndex:indexPath.row]; 
    } 
} 

我可以点击多条记录,但是当我向下滚动,我看到其他细胞也用打勾的对勾(我没有选择)。我一直在尝试这几天,有人可以帮我修复这些代码吗?

回答

0

给定的单元实例被回收并用于许多行。存储你检查过的indexPathes而不是单元格。

+0

好的,可以通过编程方式解决这个问题? – Illep 2012-01-01 10:28:15

+0

如上所示使用NSIndexSet来存储选定的单元格行索引。根据含义NSIndexSet – 2012-01-01 10:48:46

+0

,你的意思是改变allmyselectedobjects的类型为NSIndexSet而不是NSMutableArray? – Illep 2012-01-01 18:49:07

0

权利之前

Bool xx = 

补充一点:

 [cell setAccessoryType:UITableViewCellAccessoryNone]; 
0

看来您正在使用的NSIndexSet存储检查细胞。所以只需插入所选单元格的索引并进行测试。

// Test 
BOOL xx = [allmyselectedobjects containsIndex: indexPath.row] 

// Selected cell 
[allmyselectedobjects addIndex: indexPath.row] 

// Unselected cell 
[allmyselectedobjects removeIndex: indexPath.row] 
+0

没有.. allmyselectedobjects是一个NSMutableArray,我用它来存储选中的单元格 – Illep 2012-01-01 09:33:17

+0

下面的答案。 – 2012-01-01 10:28:34