在reloadData()

时间:2016-04-27 15:54:11

标签: ios xcode swift uicollectionview reloaddata

我想创建一个无限滚动集合视图,所以在这段代码中,每次索引路径等于最后一个单元格项时,我都会向单元格数添加10,然后重新加载集合中的数据。功能有效;我可以无限滚动,但如果我停下来,然后向上或向下滚动一下,一切都是空白的。细胞没有显示出来。

我的理论是它与dequeueReusableCellWithReuseIdentifier有关,它决定只显示当前在屏幕上的单元格。

View when scrolling(我将数字添加到Xcode之外的单元格中)

View with the missing cells above when scrolling a bit after stopping

private let reuseIdentifier = "Cell"
private var numberOfCells = 20

class CollectionViewController: UICollectionViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)

        if indexPath.row == numberOfCells - 1 {
            numberOfCells += 10
            self.collectionView?.reloadData() 
        }

        cell.contentView.backgroundColor = UIColor.blueColor()
        return cell
    }

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

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

4 个答案:

答案 0 :(得分:1)

reloadData拨打cellForItemAtIndexPath是不好的。使用其他委托方法,例如scrollViewDidScroll

答案 1 :(得分:1)

var numberOfCells: Int = 20 {    
    didSet {
        if numberOfCells != oldValue  {
            self.collectionView?.reloadData()
        }
    }
}

答案 2 :(得分:0)

我在Table View中做类似的事情,它对我有用。唯一的区别是,如果indexPath.row是最后一个单元格,那么我正在调用另一个函数来执行某些操作(对我来说是必需的)并且只调用reloadData()到该函数中。试试这种方式,我不确定,但它可以解决你的问题。

答案 3 :(得分:0)

Swift 4.2

像这样重新加载。

DispatchQueue.main.async(execute: collectionView.reloadData)
相关问题