2011-12-31 132 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