为由UITableViewDiffableDataSource支持的UITableView选择IndexPath

问题描述

我正在尝试使用UITableViewDiffableDataSource在UITableView上选择索引。想法是使用indexPath(for itemIdentifier: ItemIdentifierType)查找要选择的indexPaths。但是我的问题是,除非传入ItemIdentifierType的SAME实例并将其添加到DataSource中,否则indexPath()找不到任何东西。这意味着,如果您通过刷新API更新了Items,然后尝试使用存储的Items查找indexPath,它将找不到任何东西。 Hashable中表达的对象身份似乎并不是唯一的因素。

class PersonModel: Hashable {
    var identifier: String?

    func hash(into hasher: inout Hasher) {
        hasher.combine(identifier)
    }
    static func == (lhs: PersonModel,rhs: PersonModel) -> Bool {
        return lhs.identifier == rhs.identifier
    }
}

class ViewController: UIViewController {

    var diffableData: UITableViewDiffableDataSource<String,PersonModel>? = ...

    func selectIndices() {
        var snapshot = NSDiffableDataSourceSnapshot<String,PersonModel>()
        snapshot.appendSections(["Section"])

        var remotePerson: PersonModel = ... // get from API
        snapshot.appendItems([remotePerson],toSection: "Section")
        diffableData?.apply(snapshot)

        var storedPerson: PersonModel = ... // get from storage,identifier matches remotePerson's
        let indexToSelect = diffableData?.indexPath(for: storedPerson) // not working!
    }
}

找到要选择的索引的明智方法是什么?如果PersonModel是一个结构,我想要的行为似乎可行,但我不想使用该结构。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)