Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing cells in demands in UICollectionView with vertical infinite scroll

I would like to know how to achieve using a UICollectionView the desired effect of loading in demand like in the Amazon app when you make a search, it returns only a number of items until the scroll ends, then a loading indicator it set to load more cells and go on until all the products in the search it's showed.

Something like the following picture for example :

enter image description here

Normally you have to set in the numberOfItemsInSection, the number of items of the data source, how it's the way?, you set the total of items and then load it lazy or something?

Thanks in advance.

like image 934
Victor Sigler Avatar asked Jan 30 '15 23:01

Victor Sigler


2 Answers

We can use willDisplay method:

var endOfData = false

...

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if indexPath.row == model.data.count - 5 && !endOfData {
        loadNextData()
    }
}

It looks like the simplest way.

like image 66
pchelnikov Avatar answered Nov 27 '22 08:11

pchelnikov


Using the scrollViewDidScroll function like crazy_phage did above you can observe when finally reach the final of the CollectionView then you can update the numberOfRowInSections and call the reloadData in the following way :

class CollectionSampleViewController: UICollectionViewController {

    private let reuseIdentifier1 = "Cell"
    private var numberOfItemsPerSection = 9    

    override func viewDidLoad() {
       super.viewDidLoad()        
    }

    override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
    }

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
       return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return numberOfItemsPerSection
    }    

    override func scrollViewDidScroll(scrollView: UIScrollView) {
       let offsetY = scrollView.contentOffset.y
       let contentHeight = scrollView.contentSize.height

       if offsetY > contentHeight - scrollView.frame.size.height {            
          numberOfItemsPerSection += 6
          self.collectionView.reloadData()
       }
    }   
}

When the reloadData function its called the scroll remains in the same place and the new data it's loaded.

In the above code you can use an Activity Indicator View or anything else you want to add to your code.

like image 24
Victor Sigler Avatar answered Nov 27 '22 09:11

Victor Sigler