ios - 删除行后表视图具有旧索引 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
,但是,您可能会假设动画顺利消失,并且看起来粗糙且不好看。为什么表仍然通过旧索引以及如何修复它?
解决方案
一个非常简单的解决方案是通过闭包中的单元格以获得实际的索引路径
德拉雷
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)
}
旁注:重复使用单元格。使用默认初始化程序创建单元格是非常糟糕的做法。
推荐阅读
- wordpress - 按自定义字段订购 Wordpress 自定义帖子
- android - “无法解析构造函数 ArrayAdapter()”错误
- scala - 如何使用返回类型 List 在 scala 中实现洪水填充
- reactjs - 我不断收到此错误“无法读取未定义的属性‘地图’”
- jestjs - jest.mock(..) 在“describe”中不起作用(TypeError:moduleName.split 不是函数)
- javascript - 在 javascript 类中保存数据
- sql-server - 在批量插入之前计算 csv 文件中的行数,非空文件检查
- vulkan - 如何使用 Vulkan 将 hdr 文件图像映射到立方体贴图?
- tabulator - 确定制表符单元格内光标的 X/Y 坐标
- jquery - Django REST framework Ajax 调用仅适用于第一次调用