表格视图标记多个单元格Swift 3

表格视图标记多个单元格Swift 3

问题描述:

我有一个非常讨厌的问题。表格视图标记多个单元格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我完全同意你的答案,最好的解决方案。 –

这里是代码,它可以帮助你

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欢迎:) –

您需要相应地更新数据模型,以便在调用cellForRowAtIndexPath时显示包含更新内容的单元格。

如果您不使用数据模型,则需要将indexPath存储在可变数组中,并检查当前indexPath是否已标记。

希望这会有所帮助。

在您的自定义单元格

创建一个委托

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)") 

      }