首页 > 解决方案 > 如何使用 UICollectionViewCell 之间的均匀间距

问题描述

我正在尝试UICollectionView为每行显示 2 个(110x150)的单元格,左右间距均匀。

但是我试图通过使用view.frame.width单元格的和宽度来计算间距,但不幸的是我似乎做错了。

我什至尝试为单元格使用小于 110.0 的宽度,但集合视图似乎每行仅显示 1 个地窖。

UIViewController

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

    let cellWidth : CGFloat = 110.0
    //let screenWidth = screenSize.width

    let numberOfCells = floor(self.view.frame.size.width / cellWidth)
    let edgeInsets = (self.view.frame.size.width - (numberOfCells * cellWidth)) / (numberOfCells + 1)

    return UIEdgeInsetsMake(20, edgeInsets, 0, edgeInsets)
}

故事板

在此处输入图像描述

结果

在此处输入图像描述

如何让 UICollectionView 正确并排显示两个单元格,左右间距均匀?

标签: iosswiftuicollectionviewuikit

解决方案


推荐阅读