从表中选择多个记录

时间:2011-12-31 18:52:42

标签: iphone objective-c

我需要在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];
    }   
}

我可以点击多个记录,但是当我向下滚动时,我看到其他单元格也勾选了复选标记(我没有选择)。我已经尝试了好几天,有人可以帮我修复这段代码吗?

3 个答案:

答案 0 :(得分:0)

之前

 Bool xx =

添加:

        [cell setAccessoryType:UITableViewCellAccessoryNone];

答案 1 :(得分:0)

您似乎正在使用NSIndexSet来存储已检查的单元格。因此,只需插入所选单元格的索引并进行测试即可。

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

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

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

答案 2 :(得分:0)

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