简体   繁体   中英

iOS Swift update UICollectionView dynamically

Well, I have a very annoying problem of updating CollectionView's dynamically. I always get the error: "UICollectionView received layout attributes for a cell with an index que path does not exist"

I made a basic design that shows fruits, added a button to show only apple, when I click this button, grab the content just have apple and send update CollectionView and I see this error ...

Here the method who updates dynamically my CollectionView:

@IBAction func showOnlyApple(sender: AnyObject) {
    var justApple = [FruitsObject]()
    for item in self.fruitsCollection{
        if (item.name! == "Maça") {
            justApple.append(item)
        }
    }
    self.fruits = justApple
    self.uiCollectionView.reloadData()
}

If someone wants to see the error, here's the project: https://github.com/bkawakami/CollectionViewFruits

Just build the project and click the button, "Só Maçã"

Someone has passed or know how to solve this error?

Thanks!

In your CardsLayout class you are looping through a cache variable that is never updated in order to set the layout attributes. You're seeing this error because you are returning layout attributes for a cell that no longer exists in your datasource, but still exists in your cache . One way to fix this is to change your layoutAttributesForElementsInRect(rect: CGRect) to the following:

override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var layoutAttributes = [UICollectionViewLayoutAttributes]()

    // Clear the cache
    cache.removeAll()

    // Call prepare layout to repopulate the cache based on the new number of items
    prepareLayout()

    for attributes in cache {
        if CGRectIntersectsRect(attributes.frame, rect ) {
            layoutAttributes.append(attributes)
        }
    }

    return layoutAttributes
}

However, this defeats the purpose of your cache in the first place - now that you understand the issue you should be able to redesign your CardsLayout class accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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