-->

UICollectionView Custom layout reloading issue in

2019-09-09 06:51发布

问题:

This is refrence link:

https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest

I have implemented load more in UICollectionView at last cell , the data is getting downloaded, after download complete i want to reload collection

collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.reloadData()

let concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(concurrentQueue) {
            DataManager.sharedInstance.homeRequest(Dictionary: params, onSuccess: { (dict) in
                self.downloadPageIndex +=  1
                let response = HomeObject(dictionary: dict)

                for (_,e) in (response.dataDict?.enumerate())!{
                    self.dataArray.append(e)
                }

                dispatch_async(dispatch_get_main_queue()) {

                    self.collectionView.reloadData()
                    self.collectionView.collectionViewLayout.invalidateLayout()

                }
                self.activityIndicatorCell.stopAnimating()

                }, onError: { (error) in
                    self.activityIndicatorCell.stopAnimating()

            })

like this collectionview reloadata

Can any one help me out?

回答1:

Ran into your question and am currently facing the same problem, after some digging i figured it out!

The problem is within the PintrestLayout file

Inside you will find code like (PROBLEM) :

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

Basically, if the attributes that you are applying to the CollectionView are empty (they are at the start), apply the PintrestLayout to it, and thats perfect! BUT If you are reloading the data and adding to the collectionView, you need to apply the layout again, but the cache isnt empty when you try to apply the layout to the collectionView again, thus it returns and doesn't work at all...

SOLUTION :

replace that code with :

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

Now you are saying "i dont care if its empty or not, just apply the damn layout to my collectionView"

And Done! Now reloadData() will update how many cells you got...

This is pretty expensive though, if you wanna make it faster, and trim some memory etc... Then look into invalidateFlowLayout Documentation.