问题描述
我创建了一个相当简单的 tableView 来为项目模型选择一个类别。昨天一切正常。今天,我一直在尝试将 tableView 数据源切换到 UITableViewDiffableDataSource
,因为我想围绕 API。我已经备份并运行了整个 tableView,除了我无法再编辑我的行!
setEditing
逻辑的作用是当我点击导航栏中的编辑按钮时 newCategoryButton
被禁用,当我再次点击它时启用。但是,我永远无法滑动删除,并且在编辑模式下,我的行旁边没有显示删除图标。
我尝试删除 setEditing
,清空 commit editingStyle
并简单地将 canEditRow
设置为 return true
,但仍然没有。
任何帮助将不胜感激。谢谢!
override func tableView(_ tableView: UITableView,canEditRowAt indexPath: IndexPath) -> Bool {
let section = dataSource.snapshot().sectionIdentifiers[indexPath.section]
if section == .noneselected {
return false
} else {
return true
}
}
override func setEditing(_ editing: Bool,animated: Bool) {
super.setEditing(editing,animated: true)
if editing == true {
newCategoryButton.isEnabled = false
} else {
newCategoryButton.isEnabled = true
}
}
override func tableView(_ tableView: UITableView,commit editingStyle: UITableViewCell.EditingStyle,forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
categories.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath],with: .automatic)
}
}
override func tableView(_ tableView: UITableView,canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView,moveRowAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath) {
let movedCategory = categories.remove(at: sourceIndexPath.row)
categories.insert(movedCategory,at: destinationIndexPath.row)
}
screenShot after edit button is tapped
解决方法
问题在于 canEditRowAt
是一个数据源方法。您(视图控制器)现在不是数据源; diffable 数据源是。您需要在diffable数据源中实现这个方法。这通常是通过继承 diffable 数据源类来完成的,以便您可以覆盖此方法。否则,diffable 数据源只会返回其默认值 — false
,这就是您目前无法编辑任何行的原因。