0

我有一个场景,我有一个水平滚动的集合视图有许多 X 单元格。单元格的默认宽度为 71 磅。

根据 X 的值,当它们的总宽度小于集合视图的宽度时,我的单元格可能会更少,这很好。如果它们的总宽度(单元格数 * 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 
        }
    }
}

在此处输入图像描述

4

4 回答 4

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

}
于 2019-01-30T21:13:22.570 回答
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)
    }
}
于 2019-01-30T21:34:14.867 回答
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)
        }
    }
}
于 2019-01-31T11:25:52.797 回答
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)
   }
于 2019-01-31T13:17:53.440 回答