只一次调用一次collectionView cellForItemAtIndexPath -swift-以编程方式

问题描述

我有一个使用此委托和数据源设置的collectionView:

extension CardView : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{


func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
    
    let numberOfURLS = cardModel?.urlStrings?.count
    return numberOfURLS!
}

func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let videoCell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCellIdentifier",for: indexPath)
    videoCell.backgroundColor = UIColor.random()
    return videoCell
    
}


func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeforItemAt indexPath: IndexPath) -> CGSize {
    return self.bounds.size
}

}

问题在于,即使返回的单元格不止一个方法cellForItemAtIndexpath也仅被调用一次。

解决方法

collectionView(_:cellForItemAt:)仅在单元格出现或即将出现时才被调用。它不会为所有单元格调用它,而只会为可见的单元格(或即将滚动到视图中的单元格)调用它。它被称为即时。

您还可以打开预取功能(仅当您在集合视图的“尺寸检查器” IB中关闭“估算尺寸”或手动将流程布局的estimatedItemSize设置为.zero时,该功能才有效),但是相对于获取单元格(获取要滚动进入视图的单元格要早得多)而言,这只会使其更加“渴望”。它不会获取所有单元,而只是操作系统确定的单元可能会很快滚动到视图中。