Showing cells in demands in UICollectionView with vertical infinite scroll

后端 未结 3 639
别跟我提以往
别跟我提以往 2020-12-14 04:34

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 sea

3条回答
  •  时光取名叫无心
    2020-12-14 05:30

    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.

提交回复
热议问题