如何为特定单元格分配标签?

How to assign a label to a specific cell?

现在,当我在单元格上向左滑动以显示 "favorite" 按钮并单击它时,标签 "Favorite" 出现在一个随机单元格上,而不是我滑动的那个单元格上。当我点击指定的按钮时,如何在右侧单元格上制作 "Favorite" 标签 appear/disappear?

现在我在 editActionsForRowAt 函数中的代码是:

internal func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell

    let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { action, index in
        cell.favoriteLabel.text = "Favorite"
        tableView.reloadRows(at: [indexPath], with: .none)
    }
    favorite.backgroundColor = UIColor.orange

    return [favorite]
}

问题是设置 "favoriteLabel" = "Favorite" 没有将右侧单元格的 "favoriteLabel" 设置为 "Favorite"

你在这里采取了错误的方法。您应该更新数据模型,然后在索引路径处重新加载单元,而不是直接更新单元。然后您的 cellForRowAt 将根据更新的数据模型正确显示更新的单元格。

你实际上是两者的奇怪组合。您(错误地)尝试获取单元格,然后设置其标签,然后重新加载该行。不要两者都做。只需更新您的数据模型,然后重新加载该行。就是这样。

顺便说一句,永远不要在 cellForRowAt: 之外调用 dequeueReusableCell。如果您坚持当前的方法(滚动后可能无法正常工作),则需要将对 dequeueReusableCell 的调用替换为对 cellForRow(at:).

的调用