gpt4 book ai didi

ios - 基于数组比较更新 UICollectionView

转载 作者:行者123 更新时间:2023-11-30 10:53:45 26 4
gpt4 key购买 nike

我目前有一个 collectionView: UICollectionView,它基于名为 projects 的对象数组显示内容。有时我会从服务器收到一个名为 newProjects 的更新数组。 newProjects 应替换 projects 作为 collectionView 的数据源。

我找到了一种方法,当使用以下代码从数组中删除对象时更新collectionView:

var indexPaths = [IndexPath]()

for project in projects {

if(!newProjects.contains(project)) {

let index = projects.firstIndex(of: project)
indexPaths.append(IndexPath(item: index!, section: 0))
}
}

collectionView.deleteItems(at: indexPaths)

projects = newProjects
collectionView.reloadData()

这适用于已删除的项目。然而,我也在尝试对添加的项目使用react。然而,我的代码似乎失败了,因为我不断收到异常:

Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (65) must be equal to the number of items contained in that section before the update (64), plus or minus the number of items inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).

我添加的项目比较的代码是:

// First, the deletion from the code above is called.
// project = newProjects and data reload doesn't happen after deletion.

var addIndexPaths = [IndexPath]()

for project in newProjects {

if(!projects.contains(project)) {

projects.append(content)
addIndexPaths.append(IndexPath(item: projects.count - 1, section: 0))
}
}

collectionView.insertItems(at: addIndexPaths)

projects = newProject
collectionView.reloadData()

我确信这段代码有点像黑客工作(因为它不起作用),但老实说我不知道​​如何才能可靠地更新 UICollectionView。有人有建议或有用的链接吗?干杯!

最佳答案

Wez指出,仅仅取出所有数据的插入和删除确实最终起作用了。现在整个调用就简化为:

projects = newProjects
collectionView.reloadData()

我最初认为这不起作用,但那是由于服务器出现问题。我还没有尝试过,认为我需要手动插入所有更改的项目。

rmaddy指出,从原始代码中取出 reloadData() 也有效!由于某种原因,我最初的想法是在添加和删除项目后需要 reloadData() ,可能是因为我还认为 UITableViews 需要您调用 endUpdates() ...我使一些基本概念过于复杂化。

谢谢大家!

关于ios - 基于数组比较更新 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54183551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com