【问题标题】:Resizing UICollectionView with Custom Layout after adding or deleting cells in swift using Pinterest cell使用 Pinterest 单元格快速添加或删除单元格后,使用自定义布局调整 UICollectionView 的大小
【发布时间】:2020-03-30 08:58:54
【问题描述】:

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

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

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

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

请帮忙。

【问题讨论】:

  • 尝试使用collectionView.collectionViewLayout?.invalidate

标签: ios swift uicollectionview uicollectionviewlayout pinterest


【解决方案1】:

终于,我找到了答案。

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

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

在同一个函数中。它现在终于可以工作了。

【讨论】:

  • 谢谢你的想法!!但不明白你为什么同时检查缓存的空和非空条件。这对我来说没有意义。
【解决方案2】:

在上述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() -&gt; Int 添加到 PinterestLayoutDelegate

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多