2

我创建了一个相当简单的 tableView 来为项目模型选择类别。昨天一切正常。今天,我一直在尝试将 tableView 数据源切换到 a UITableViewDiffableDataSource,因为我想围绕 API 进行思考。我已经备份并运行了整个 tableView,除了我不能再编辑我的行了!

当我点击导航栏中的编辑按钮时,该setEditing逻辑newCategoryButton被禁用,当我再次点击它时,该逻辑被启用。但是,我永远无法滑动删除,并且在编辑模式下,删除图标不会显示在我的行旁边。

我尝试删除setEditing,清空commit editingStyle并简单地设置canEditRowreturn 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)
}

点击编辑按钮后的屏幕截图

4

1 回答 1

2

麻烦的是那canEditRowAt是一个数据源方法。您(视图控制器)现在不是数据源;可区分的数据源是。您需要在 diffable 数据源中实现此方法。这通常通过子类化 diffable 数据源类来完成,以便您可以覆盖此方法。否则,可区分数据源只会返回其默认值 — 即false,这就是您目前无法编辑任何行的原因。

于 2021-06-07T21:57:23.747 回答