UICollectionViewCell 的间距优先于大小

Prioritize spacing over size for UICollectionViewCell

我有一个 UICollectionView,我希望每行有 3 个单元格。我想每个单元格之间有一个固定的间距,单元格的大小动态调整。

是的,我可以设置最小单元格间距。但是我希望这个间距是固定的。如何在单元格大小调整时将单元格之间的间距设置为恒定?

我是这样解决的:

extension ViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        //Calculate cell width
        let spacingTotal = CGFloat((cellSpacing * 2) + (marginSpacing * 2))
        let screenWidth = UIScreen.main.bounds.width
        let cellWidth = (screenWidth - spacingTotal) / 3.0

        //Maintain ratio for cell height
        let widthToHeighRatio = CGFloat(102 / 94)
        let cellHeight = cellWidth * widthToHeighRatio

        return CGSize(width: cellWidth, height: cellHeight)
    }
}

其中 cellSpacing 是最小单元格间距的值。 margingSpacing 是 collectionView 的左右边距的总值。

另请注意,我保持单元格大小的比率;我正在使用的设计显示一个 102 x 94 的单元格,因此我为每个屏幕尺寸保持该比例。

这是它在 iPhone SE 和 iPhone X 上的样子:

实现 sizeForItem 并点 his ,假设间距为 10

width = (self.view.frame.size.width -  2 * 10)/3