ios - 数据更改后更新 tableViewCells 属性

标签 ios swift swift3

我在 tableViewController 中显示了一组 list 项目。每个项目都包含在tableViewCell中,当检查一个项目时,该单元的背景颜色会从白色变为绿色。我可以选中和取消选中项目,并且单元格的颜色会按预期变化。

我添加了一个重置​​按钮,将所有项目更改为未选中状态。我测试了重置功能,项目正在重置,但是 tableViewCells 没有更新为正确的颜色,它们保持在最后的状态。我试过使用

tableView.reloadData()

tableView.reloadRows()

但这似乎对细胞没有任何影响。

我的重置函数位于模型中:

func resetCheckedStatus(for items: [Item]) -> [Item] {
  var resetItems: [Item] = []

  for item in items {
      item.isChecked = false
      resetItems.append(item)
  }
  return resetItems
}

我在 tableViewController 中的重置操作

    @IBAction func resetItems(_ sender: Any) {

    let title = "Reset Items"
    let message = "Are you sure you want to reset all items to unchecked status?"

    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    let okAction = UIAlertAction(title: "OK", style: .default, handler: {action in self.items = resetCheckedStatus(for: self.items)} )
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

    alert.addAction(cancelAction)
    alert.addAction(okAction)

    present(alert, animated: true, completion: nil)
    self.tableView.reloadData()

    if let indexPaths = self.tableView.indexPathsForVisibleRows {
        tableView.reloadRows(at: indexPaths, with: .automatic)
    }
}

最佳答案

您需要在更改项目数组后重新加载 TableView 。将重新加载 TableView 代码移动到 okAction 的处理程序 block 中,如下所示

let okAction = UIAlertAction(title: "OK",  
                             style: .default, handler{action in
                            self.items = resetCheckedStatus(for: self.items)
                                         self.tableView.reloadData()} )

关于ios - 数据更改后更新 tableViewCells 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44014112/

相关文章:

ios - UITableViewRowAction 和 UIAlertController

ios - 在应用程序和网站上销售内容

ios - Apple Vision框架–从图像中提取文本

json - 未使用初始化程序的结果

swift - 返回上一个 View 时 AVPlayer 不会停止播放

ios - Facebook 按钮委托(delegate)无法正常工作

ios - 在没有单元格的情况下为 UICollectionView 启用弹跳/滚动

ios - swift 4 : Set Different Date and Time

ios - 如何知道 UIPageViewController 在其父 UIViewController 中的当前状态

ios - 如何在iOS中将图像数据上传到服务器?