0

我正在尝试过滤 TableViewDiffableDataSource 中的用户列表。过滤后的用户数组传递给以下函数:

private func updateUserCell(_ users: Users? = nil) {

        guard let newUsers = users else {

            print("No users to show")

            return

        }

        snapShot.deleteItems(viewModel.userList)

        dataSource!.apply(snapShot, animatingDifferences: false)

        if newUsers == [] { return }

        var snapShot = dataSource?.snapshot()

        snapShot?.appendItems(newUsers, toSection: .main)

        dataSource!.apply(snapShot!, animatingDifferences: true)

    }

调试显示用户已正确附加到快照中。但应用显示正确数量的过滤用户,但仅显示完整列表顶部的用户。

即,如果我有完整的用户列表 [Chloe、Max、John、Martin]。搜索“jo”只会显示 Chloe。搜索“ma”会显示 Chloe 和 Max,而不是 Max 和 Martin。

4

1 回答 1

0

我不确定我是否完全理解上述方法背后的逻辑,但除非我遗漏了一些片段没有明确说明的内容,否则一种更简单的方法似乎只是用所需的用户创建一个新快照并应用那,而不是修改现有的。

private func updateUserCell(_ users: Users? = nil) {
  guard let newUsers = users, !newUsers.isEmpty else {return}

  var snapshot = NSDiffableDataSourceSnapshot<Section, User>()
  snapshot.appendSections([.main])
  snapshot.appendItems(newUsers, toSection: .main)
  dataSource.apply(snapshot, animatingDifferences: true)
}

注意。有一个默认为 nil 的更新用户方法,因此退出似乎是一个奇怪的设计选择。它表明调用它背后的逻辑有点歪曲。

于 2022-02-08T17:57:18.437 回答