使用 Pinterest 单元格在 swift 中添加或删除单元格后,使用自定义布局调整 UICollectionVie



我从以下位置下载了我的 CollectionView 的 Pintrest 自定义布局: https://www.raywenderlich.com/4829472-uicollectionview-custom-layout-tutorial-pinterest

所以布局工作正常,我设置好了,所以当你滚动到底部时,我需要让它像分页功能一样实现。

问题:如果用户在数组中添加或删除数据,则单元格不会反映其布局。例如:如果我第一次在数组中有 35 个对象并且我删除了 5 条记录,那么可滚动在显示时应固定为 32 个对象,直到 35 个对象,但在删除的情况下记录显示正确。但是,如果我们在运行时添加接下来的 35 个对象,那么我的数组有 70 条记录,但集合视图没有重新加载数据,它仍然显示 35 条记录。

在删除的情况下,如何删除此空格? 以及如何重新加载它并在添加时显示更多单元格?

请帮忙。

终于,我找到了答案。

只需注释下面用准备函数编写的代码

guard cache.isEmpty == true, let collectionView = collectionView
else {
return
}

并在注释了上面的代码之后,编写以下给定的代码:

cache.removeAll()
guard cache.isEmpty == true || cache.isEmpty == false, let collectionView = collectionView else {
return
}
contentHeight = 0

在相同的函数中。它现在终于可以工作了。

在上面cache.isEmpty == true || cache.isEmpty == false的情况下,您实际上并没有检查有关缓存元素的任何内容。代码与guard let collectionView = collectionView else {return}相同

这不是准备布局的正确方法。如果向缓存添加新项,则不应重新计算现有元素。这不仅是不必要的操作,而且是糟糕的用户体验。当用户向下滚动时,现有项目的单元格将立即更改。

要正确处理附加新元素,您可以这样做;guard cache.isEmpty || collectionViewItemCount > cache.count, let collectionView = collectionView else { return }

override func prepare() {
let collectionViewItemCount = delegate?.numberOfItemsInCollectionView() ?? 0
guard cache.isEmpty || collectionViewItemCount > cache.count, let collectionView = collectionView else { return }

.
.
.

// set the last cached item's height to the yOffSet 
for index in 0..<yOffset.count {
yOffset[index % numberOfColumns] = cache.last(where: {$0.indexPath.row % numberOfColumns == index % numberOfColumns})?.frame.maxY ?? 0
}

for item in 0..<collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
if indexPath.row >= cache.count {
.
.
.
cache.append(attributes)
.
.
.        
}
}
}

p.s.:您还需要将func numberOfItemsInCollectionView() -> Int添加到 PinterestLayoutDelegate

最新更新