如果最后一个UICollectionViewCell的总宽度大于UICollectionView的宽度,则剪辑它们

时间:2019-01-30 20:35:14

标签: ios swift collectionview uicollectionviewflowlayout

我有一个场景,其中我有一个水平滚动收集视图,其中包含多个X单元格。单元格的默认宽度为71点。

取决于X的值,当它们的总宽度小于集合视图的宽度时,我的单元格可能会更少,这很好。 如果Bun的总宽度(单元格数* 71)大于collectionView的宽度,请显示完全适合的单元格Y以及下一个单元格的一半,因此用户知道水平滚动。

这就是我现在拥有的

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if dataSource.count * 71 <= collectionView.bounds.width {
            return CGSize(width: 71, height: collectionView.bounds.height)
        } else {
            // if it's larger just show Y number of cells with the last one visible cut in half, so the user knows it's horizontally scrollable 
        }
    }
}

enter image description here

4 个答案:

答案 0 :(得分:0)

在使最后一个集合视图单元出队时,尝试更新CollectionView的宽度,如下所示:

 func dequeueReusableCell(withReuseIdentifier identifier: String, 
                     for indexPath: IndexPath) -> UICollectionViewCell {
 let cell = ....
 if cell.width < 71 {
  collectionView.width = collectionView.width - 71 +cell.width
  self.layoutIfNeeded()
 }

}

答案 1 :(得分:0)

像这样吗?

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
    let targetWidth: CGFloat = 71
    if dataSource.count * targetWidth <= collectionView.bounds.width {
        return CGSize(width: targetWidth, height: collectionView.bounds.height)
    } else {
        let numberOfCellsToFit = Int(collectionView.bounds.width / targetWidth)
        let cellWidth = collectionView.bounds.width / (CGFloat(i) - 0.5)
        return CGSize(width: cellWidth, height: collectionView.bounds.height)
    }
}

答案 2 :(得分:0)

您可以尝试以下代码:

    extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if dataSource.count * 71 <= collectionView.bounds.width {
            return CGSize(width: 71, height: collectionView.bounds.height)
        } else {
            return CGSize(width:(collectionView.bounds.width/4) * 3, height: collectionView.bounds.height)
        }
    }
}

答案 3 :(得分:0)

找到了我的解决方案,谢谢大家的帮助

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    let collectionViewWidth = self.width
    let numberOfCellsToFit = round(collectionViewWidth / cellWidth)
    let spaceBetweenCells = (collectionViewWidth - cellWidth/2) / (numberOfCellsToFit - 1)

    return (spaceBetweenCells - cellWidth)
   }