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

Clip last UICollectionViewCell if their total width is greater the UICollectionView width

我有一个场景,我有一个水平滚动的集合视图,其中包含许多 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 
        }
    }
}

在最后一个集合视图单元格出队时尝试更新 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()
 }

}

是这样的吗?

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)
    }
}

您可以试试这个代码:

    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)
        }
    }
}

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

 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)
   }