2017-02-10 50 views
4

我有一個非常討厭的問題。表格視圖標記多個單元格Swift 3

我有一個或多或少50個單元格的tableView,顯示一些選項,我可以選擇我想要的。我在Apple的文檔中讀到,默認情況下,單元在不顯示時會被重用。這樣,如果我選擇第一個單元格,每6個單元格1被標記,也就是說,如果我選擇了前6個單元格,表格中的所有單元格都將被標記!

我的表格視圖允許多項選擇。選擇是這樣做的:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark 
} 

我該如何解決這個問題?我知道你有這樣的「prepareForReuse()」的子類,這是解決方案嗎?如果是這樣,你能給我一個你如何做的例子嗎?

+0

可以顯示更多的代碼。?? –

+1

你可以帶一個Mutablearray。當用戶單擊一個單元格,然後將該單元格的索引路徑存儲到該數組中,然後再次選擇相同的單元格時,如果是,則檢查數組中已有的索引路徑,然後從數組中刪除indexpath或將indexpath添加到數組中 –

+0

@Jecky Modi我完全同意你的答案,最好的解決方案。 –

回答

3

這裏是代碼,它可以幫助你

var arr_selectedindePath = NSMutableArray() 
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
    { 
     if arr_selectedindePath .contains(indexPath) { 

      arr_selectedindePath .remove(indexPath) 
      tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none 
     } 
     else 
     { 
      arr_selectedindePath .add(indexPath) 
      tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark 
     } 

    } 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    { 

     let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! 
     if arr_selectedindePath .contains(indexPath) { 
      cell.accessoryType = .checkmark 
     } 
     else 
     { 
      cell.accessoryType = .none 
     } 

    } 
+0

你的例子工作得很好,我的朋友。非常感謝你! –

+0

@RodrigoFuscaldi歡迎:) –

3

您需要相應地更新數據模型,以便在調用cellForRowAtIndexPath時顯示包含更新內容的單元格。

如果您不使用數據模型,則需要將indexPath存儲在可變數組中,並檢查當前indexPath是否已標記。

希望這會有所幫助。

-1

在您的自定義單元格

創建一個委託

protocol CellDelegate { 

    func didTapOnButton(_ cell:Cell) 

} 

申報委託

var delegate:CellDelegate? 

3.Override這種方法

override func prepareForReuse() { 
     super.prepareForReuse() 
     self.delegate = nil 
    } 


@IBAction func buttonTapped() 
{ 
    self.delegate!.didTapOnButton(self) 
} 

在你的tableview控制器

1.Implement委託方法

2.Inside的cellForRowAtIndexPath分配標籤值cell.button

3.implement這種方法

func didTapOnButton(_ cell: Cell) { 
       print("off button clicked at index \(cell.button.tag)") 

      } 
相關問題