2011-12-05 30 views
4

我想打一個表,用戶可以選擇和一個對勾取消:如何刪除另一次點擊複選標記?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath 
{ 
    ...; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
} 

- (void)tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    ...; 
    newCell.accessoryType = UITableViewCellAccessoryCheckmark; 
    ...; 
} 

我試圖卸下檢查標記的單元點擊時再複選標記,但它需要2次點擊到那樣做而不是一個。

如果我設置的選擇樣式爲默認,當我點擊所選行,它消除了藍色的亮點;再次點擊,它會刪除複選標記。

我也嘗試了一些條件語句didSelectRowAtIndexPath,但他們只是第二次點擊和迴應。

是什麼導致了這個問題,我該如何解決它?

回答

14

你可以試試這個:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSUInteger index = [[tableView indexPathsForVisibleRows] indexOfObject:indexPath]; 

    if (index != NSNotFound) { 
    UITableViewCell *cell = [[tableView visibleCells] objectAtIndex:index]; 
    if ([cell accessoryType] == UITableViewCellAccessoryNone) { 
     [cell setAccessoryType:UITableViewCellAccessoryCheckmark]; 
    } else { 
     [cell setAccessoryType:UITableViewCellAccessoryNone]; 
    } 
    } 
} 

這應該切換每個觸摸細胞的複選標記。 如果你還只需要一個單元格在一個時間顯示爲被選中,還增加以下內容:

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSUInteger index = [[tableView indexPathsForVisibleRows] indexOfObject:indexPath]; 
    if (index != NSNotFound) { 
     UITableViewCell *cell = [[tableView visibleCells] objectAtIndex:index]; 
     [cell setAccessoryType:UITableViewCellAccessoryNone]; 
    } 
} 

如果你不想藍色高亮背景做,只需將電池的選擇樣式設置爲UITableViewCellSelectionStyleNone一旦你創建細胞。

+0

偉大的解決方案,非常感謝! –

+0

真棒先生奧利弗........非常感謝你:) –

0

檢查this蘋果官方文檔

最好的解決方案不斷

+3

爲什麼這是'有史以來最好的解決方案'? – 2012-06-21 13:00:10

0
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
     if (index != NSNotFound) { 
       UITableViewCell *cell = [[tableView visibleCells] objectAtIndex:index]; 
       if (cell.accessoryType == UITableViewCellAccessoryNone) 
       cell.accessoryType = UITableViewCellAccessoryCheckmark; 
      else 
       cell.accessoryType = UITableViewCellAccessoryNone; 
      [self.tableName reloadData]; 
     } 
} 

這有助於在切換複選標記基於

1

(再次檢查標記的細胞,當點擊刪除複選標記)初學者鏈接到蘋果文檔(我的代碼在Swift 3中):

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    tableView.deselectRow(at: indexPath, animated: true) 
    if let cell = tableView.cellForRow(at: selectedIndexPath) { 
     cell.accessoryType = .none 
    } 
    if let cell = tableView.cellForRow(at: indexPath) { 
     cell.accessoryType = .checkmark 
    } 
    selectedIndexPath = indexPath 
} 

重點是跟蹤當前選定的單元格並相應地更改cell.accessoryType。另外不要忘記根據selectedIndexPath在tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath)中正確設置cell.accessoryType。

相關問題