2016-04-27 49 views
0

我想创建一个无限滚动集合视图,因此在此代码中,每次索引路径与最后一个单元格项相等时,我将单元数加10,然后重新加载数据在集合中。该功能起作用;我可以无限滚动,但如果我停下来,然后向上或向下滚动一下,一切都是空白的。细胞没有显示。UICollectionViewCells在reloadData()后不显示()

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

View when scrolling(I加入的数字到细胞的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 
    } 
} 

回答

1

reloadData调用从cellForItemAtIndexPath是坏的。使用其他委托方法,例如scrollViewDidScroll

+0

这工作。谢谢! – noanoanoa

0

我在表视图中做类似的事情,它为我工作。唯一的区别是,如果indexPath.row是最后一个单元格,那么我正在调用另一个功能,它执行某些操作(我需要)并仅将reloadData()调用到该功能中。尝试这种方式,我不确定,但它可能会解决您的问题。

0
var numberOfCells: Int = 20 {  
    didSet { 
     if numberOfCells != oldValue { 
      self.collectionView?.reloadData() 
     } 
    } 
} 
相关问题