【问题标题】:Selecting TableView Cell Activates Checkmark in Rows in Multiple Sections选择 TableView 单元格会激活多个部分中的行中的复选标记
【发布时间】:2021-04-30 05:21:24
【问题描述】:

I've implemented checkmarks (when row is selected) with the following code in cellForRowAt:

// Add a checkmark to row when selected
    if selectedIngredients.contains(indexPath.row) {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }

但是,当我选择一行时,each 部分中的 index.row 会获得复选标记:

这似乎是因为我只指定了 indexPath.row,而不是节。我该如何编写代码以便在我选择的部分中选择的行获得复选标记?

【问题讨论】:

  • 请添加更多代码

标签: ios swift uitableview tableview accessorytype


【解决方案1】:

使用数据存储来保存复选标记,如下所示:

var selectedIngredients: Set<IndexPath> = [] // use set for unique save

然后 didSelect 回调:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if self.selectedIngredients.contains(indexPath) {
            self.selectedIngredients.remove(indexPath)
            
        } else {
            self.selectedIngredients.insert(indexPath)
        }
        
        self.tableView.reloadData()
    }

在 CellForRow 中重新加载后:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if selectedIngredients.contains(indexPath) {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }
}

如果你希望它只有一行包含复选标记:

var selectedIngredients: IndexPath? = nil

和 didSelect 回调:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
            self.selectedIngredients = indexPath
        }

最后:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if selectedIngredients == indexPath {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }
    }

【讨论】:

    【解决方案2】:

    您应该在 didSelect 中添加复选标记并在 didDeselect 方法中删除它们;

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        // update cell here
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // update cell here
    }
    

    另外,看看这个答案; https://stackoverflow.com/a/34962963/13754736

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 2023-04-04
      相关资源
      最近更新 更多