简体   繁体   English

集合视图的自定义布局不会更新

[英]Custom Layout for Collection view doesn't update

I am using the following code in order to have a UICollectionView with variable height for various cells: 我正在使用以下代码,以使UICollectionView的各个单元格具有可变的高度:

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return totalItems
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        totalItems -= 1

        collectionView.deleteItems(at: [indexPath])
        collectionView.collectionViewLayout.invalidateLayout()
    }
}

extension InviteViewController : PinterestLayoutDelegate {

    // 1. Returns the cell height
    func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat {
        print("have: ", indexPath.item)
        if(indexPath.item % 3 == 0) {
            return 150
        } else if(indexPath.item % 3 == 1) {
            return 200
        } else {
            return 250
        }
    }
}

However I see that the layout doesn't update after the deletion of the UICollectionViewCell and I get errors as: 但是我看到删除UICollectionViewCell后布局不会更新,并且出现如下错误:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: {length = 2, path = 0 - 7}' ***由于未捕获的异常“ NSInternalInconsistencyException”而终止应用程序,原因:“ UICollectionView接收到索引路径不存在的单元格的布局属性:{length = 2,path = 0-7}”

I am stuck and unable to understand why this happens and how to solve this. 我被困住了,无法理解为什么会发生这种情况以及如何解决。 Please help me find a solution for the same. 请帮助我找到相同的解决方案。 Thank you. 谢谢。

In case you want to have a look at the layout file I used, please have a look here: 如果要查看我使用的布局文件,请在这里查看:

import UIKit

protocol PinterestLayoutDelegate: class {
    // 1. Method to ask the delegate for the height of the image
    func collectionView(_ collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat
}

class PinterestLayout: UICollectionViewLayout {
    //1. Pinterest Layout Delegate
    weak var delegate: PinterestLayoutDelegate!

    //2. Configurable properties
    fileprivate var numberOfColumns = 2
    fileprivate var cellPadding: CGFloat = 3

    //3. Array to keep a cache of attributes.
    fileprivate var cache = [UICollectionViewLayoutAttributes]()

    //4. Content height and size
    fileprivate var contentHeight: CGFloat = 0

    fileprivate var contentWidth: CGFloat {
        guard let collectionView = collectionView else {
            return 0
        }
        let insets = collectionView.contentInset
        return collectionView.bounds.width - (insets.left + insets.right)
    }

    override var collectionViewContentSize: CGSize {
        return CGSize(width: contentWidth, height: contentHeight)
    }

    override func prepare() {
        // 1. Only calculate once
        guard cache.isEmpty == true, let collectionView = collectionView else {
            return
        }
        // 2. Pre-Calculates the X Offset for every column and adds an array to increment the currently max Y Offset for each column
        let columnWidth = contentWidth / CGFloat(numberOfColumns)
        var xOffset = [CGFloat]()
        for column in 0 ..< numberOfColumns {
            xOffset.append(CGFloat(column) * columnWidth)
        }
        var column = 0
        var yOffset = [CGFloat](repeating: 0, count: numberOfColumns)

        // 3. Iterates through the list of items in the first section
        for item in 0 ..< collectionView.numberOfItems(inSection: 0) {

            let indexPath = IndexPath(item: item, section: 0)

            // 4. Asks the delegate for the height of the picture and the annotation and calculates the cell frame.
            let photoHeight = delegate.collectionView(collectionView, heightForPhotoAtIndexPath: indexPath)
            let height = cellPadding * 2 + photoHeight
            let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height)
            let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)

            // 5. Creates an UICollectionViewLayoutItem with the frame and add it to the cache
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            attributes.frame = insetFrame
            cache.append(attributes)

            // 6. Updates the collection view content height
            contentHeight = max(contentHeight, frame.maxY)
            yOffset[column] = yOffset[column] + height

            column = column < (numberOfColumns - 1) ? (column + 1) : 0
        }
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()

        // Loop through the cache and look for items in the rect
        for attributes in cache {
            if attributes.frame.intersects(rect) {
                visibleLayoutAttributes.append(attributes)
            }
        }
        return visibleLayoutAttributes
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return cache[indexPath.item]
    }

}

I followed: https://www.raywenderlich.com/392-uicollectionview-custom-layout-tutorial-pinterest 我遵循了: https : //www.raywenderlich.com/392-uicollectionview-custom-layout-tutorial-pinterest

override func prepare() {
    // 1. Only calculate once
    guard cache.isEmpty == true, let collectionView = collectionView else {
        return
    }

In this part delete guard cache.isEmpty == true, . 在这一部分中,删除guard cache.isEmpty == true, It works. 有用。

extension CategoryPageVC: PinterestLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView,
                        heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat {

let rate = self.categoryData[indexPath.item].image.size.width / self.collectionView.frame.size.width * 2
        return self.categoryData[indexPath.item].image.size.height / rate
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM