使用垂直无限滚动在UICollectionView中显示需求中的单元格

Vic*_*ler 8 scroll uicollectionview swift ios8

我想知道如何使用UICollectionView所需的加载效果,如在亚马逊应用程序中进行搜索时,它只返回一些项目,直到滚动结束,然后加载指示器设置为加载更多的单元格并继续,直到它显示的搜索中的所有产品.

像下面这样的图片:

在此输入图像描述

通常你必须设置,numberOfItemsInSection数据源的项目数,它是如何的方式?,你设置项目的总数,然后加载它懒惰或什么?

提前致谢.

Vic*_*ler 7

使用scrollViewDidScroll像crazy_phage这样的函数,你可以观察到最后到达CollectionView的最后,然后你可以更新numberOfRowInSectionsreloadData以下面的方式调用:

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()
       }
    }   
}
Run Code Online (Sandbox Code Playgroud)

reloadData它被称为滚动的函数保持在同一位置并且加载它的新数据时.

在上面的代码中,您可以使用活动指示器视图或您要添加到代码中的任何其他内容.


cra*_*age 5

我也在 UICollectionView 上进行无限滚动。这是您需要的功能。

func scrollViewDidScroll(scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height
    if offsetY > contentHeight - scrollView.frame.size.height {
        println("this is end, see you in console")
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在 if 子句中编写代码。reloadData()我认为。

// load data for collection view
func loadGroundData(){
    AVCloud.callFunctionInBackground("GroundWaterFallList", withParameters: [:]) {
        (result: AnyObject!, error: NSError!) -> Void in
        if error == nil {
            NSLog("ground users count: \(result.count)")
            NSLog("\(result[0])")
            self.ground_water_fall_people = result as NSArray
            self.collectionView?.reloadData()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

嗯,我还在努力,希望这有帮助。并希望有人可以解释这两个功能。 collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) scrollViewDidScroll


pch*_*kov 5

我们可以使用 willDisplay 方法:

var endOfData = false

...

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

这看起来是最简单的方法。