2010-07-13 86 views
0

我有這個奇怪的問題。我正在用XCode創建一個清單程序,我正在使用帶有UITableViewCellAccessoryCheckmark的UITableView。我可以選擇單元格,並且會出現複選標記,但不知何故,下面還沒有選中的其他單元格也會出現複選標記。有任何想法嗎?
這裏是我的複選標記編碼:UITableView清單問題

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
UITableViewCell *cell; 
cell = [aTableView cellForRowAtIndexPath: indexPath]; 
cell.accessoryType = UITableViewCellAccessoryCheckmark; 

} 

我不知道這是否會影響它,但我也實現了這個方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"CellIdentifier"; 

// Dequeue or create a cell of the appropriate type. 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    cell.accessoryType = UITableViewCellAccessoryNone; 
} 

// Configure the cell. 
if(tableView == Table1){ 

    switch(indexPath.section){ 
     case 0: 
      cell.textLabel.text = [array1 objectAtIndex:indexPath.row]; 
      break; 
     case 1: 
      cell.textLabel.text = [array2 objectAtIndex:indexPath.row]; 
      break; 
     case 2: 
      cell.textLabel.text = [array3 objectAtIndex:indexPath.row]; 
      break; 
    } 

    //cell.textLabel.text = [NSString stringWithFormat:@"Row %d", indexPath.row]; 
} 
if(tableView == Table2){ 
    cell.textLabel.text = [array4 objectAtIndex:indexPath.row]; 
} 
return cell; 

}

感謝。

+0

你可以分享你的''tableView:cellForRowAtIndexPath:''的實現嗎? – Prairiedogg 2010-07-13 19:51:32

+0

我同意Prairiedogg,讓我們看看其餘的代碼。您可能會重複使用單元格,因此不會重置其狀態。 – raidfive 2010-07-13 20:10:57

+0

我添加了實現。 – CSwat 2010-07-13 20:11:54

回答

2

每次撥打電話tableView:cellForRowAtIndexPath:時,請設置cell.accessoryType。否則,當你重用一個單元格時,你會得到它的accessoryView而不是你所期望的。

所以,是的,你需要跟蹤什麼時候通過某種方法選擇NSIndexPaths,而不僅僅是查看accessoryType

+0

對不起,但你能給我一個例子,我將如何重置cell.accessoryType?你是否告訴我保留一個選定的單元格列表,並相應地顯示其配件類型,每次調用tableView:cellForRowAtIndexPath:? – CSwat 2010-07-13 20:45:13

+0

是的,保留所選單元格的列表,或者提出一些其他數據結構來跟蹤信息。邁克爾的想法是使用字典放置文本和選擇鍵是我用過的一種技巧。然後在設置單元格標題的同時設置附件類型。 您需要每次都設置附件類型,因爲您不是爲每一行都創建一個新單元格 - 您經常重新使用現有(屏幕外)單元格。不要考慮重新使用現有的單元 - 通過限制單元分配來獲得真正的性能提升。 – Jablair 2010-07-14 05:39:59

2

您應該在數據源(數組)中保留選中/未選中的信息。我建議您刪除cell.accessoryType = UITableViewCellAccessoryNone;行。
該行僅對少數第一個單元格執行。所有其他單元格將被「重用」 - 意味着將使用舊的(已啓動的)單元格,並且您將不得不修改這些單元格上顯示的詳細信息(全部在cellForRowAtIndexPath之內,就像您現在所做的那樣)。

此外,你將不得不添加一個類似的行(類似cell.accessoryType = ([[array objectAtIndex:indexPath.row] boolValue] ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;)。

一般來說,我建議你使用一個數組來保存你的表的數據,當數組中的每一項都將是一個字典。通過這種方式,您將能夠保存文本和布爾對號(在NSNumber內)並在需要時輕鬆訪問它們。