首页 > 解决方案 > 删除行后表视图具有旧索引 Swift

问题描述

我有删除一些行的表格视图,其中包含以下内容:

func deleteRows(_ indecies: [Int]) {
    guard !indecies.isEmpty else { return }
    let indexPathesToDelete: [IndexPath] = indecies.map{ IndexPath(row: $0, section: 0)}
    let previousIndex = IndexPath(row: indecies.first! - 1, section: 0)
    tableView.deleteRows(at: indexPathesToDelete, with: .none)
    tableView.reloadRows(at: [previousIndex], with: .none)
  }

cellForRow我有像这样“点击”关闭的单元格:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard indexPath.row < presenter.fields.count else { return EmptyCell() }
    let field = presenter.fields[indexPath.row]
    switch field.cellType {
    case .simple:
      guard let model = field as? SimpleTextItem else { return EmptyCell() }
      let cell = SimpleTextCell()
      cell.setup(label: LabelSL.regularSolidGray(), text: model.text, color: Theme.Color.bleakGray)
      return cell
    case .organization:
      guard let model = field as? OrganizationFilterItem else { return EmptyCell() }
      let cell = OrganizationFilterCell()
      cell.setup(titleText: model.title,
                 holdingNumberText: model.holdingNumberText,
                 isChosed: model.isChosed,
                 isHolding: model.isHolding,
                 isChild: model.isChild,
                 bottomLineVisible: model.shouldDrawBottomLine)

      cell.toggleControlTapped = {[weak self] in
        self?.presenter.tappedItem(indexPath.row)
      }
      return cell
    }
  }

什么时候

cell.toggleControlTapped = {[weak self] in
            self?.presenter.tappedItem(indexPath.row)
          }

删除行后点击,索引通过是错误的(它是旧的)。例如,我有 10 行,我删除 2-3-4-5 行,然后点击 2 行(删除前是 6 行)。该方法通过“6”而不是“2”。

问题实际上是通过tableView.reloadData(在函数中添加 )来解决的deleteRows,但是,您可能会假设动画顺利消失,并且看起来粗糙且不好看。为什么表仍然通过旧索引以及如何修复它?

标签: iosswift

解决方案


一个非常简单的解决方案是通过闭包中的单元格以获得实际的索引路径

德拉雷

var toggleControlTapped : ((UITableViewCell) -> Void)?

叫它

toggleControlTapped?(self)

处理它

cell.toggleControlTapped = {[weak self] cell in
    guard let actualIndexPath = self?.tableView.indexPath(for: cell) else { return }
    self?.presenter.tappedItem(actualIndexPath.row)
}

旁注:重复使用单元格。使用默认初始化程序创建单元格是非常糟糕的做法。


推荐阅读