单元格间距为零的 UICollectionView

UICollectionView with zero cell spacing

我已经按照 并尝试每行实现 5 个单元格,当我检查 iPhone 6 & iPhone SE 时效果很好,如下所示。

但是当我尝试在 iPhone 6 Plus 上 运行 时出现了问题。谁能帮我解决这个问题?

这是我的代码。

screenSize = UIScreen.main.bounds
screenWidth = screenSize.width
screenHeight = screenSize.height
let itemWidth : CGFloat = (screenWidth / 5)

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 10.0, left: 0, bottom: 10.0, right: 0)
collectionView!.collectionViewLayout = layout

必须是

let itemWidth : CGFloat = (screenWidth / 5.0)

所以结果不会四舍五入。

已更新

请确保如果您使用故事板来创建您的 UICollectionView,请记住将自动布局设置为集合视图的大小,以便它更新为任何当前屏幕大小。

更新 2

如果您使用故事板,则无需创建 UICollectionViewFlowLayout。您可以从情节提要中设置插图和间距。 然后在您的 .m 文件中执行此操作以确定项目的大小。

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
     return yourDesiredSize;
}

要修复空格,每个单元格的大小应该是一个整数。那么四舍五入后的数之和与collectionView大小之差可以平均分配或者放在一个单元格中。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // To avoid white space inbetween cells we're rounding the width of each cell
    var width = CGFloat(floorf(Float(screenWidth/CGFloat(objects.count))))
    if indexPath.row == 0 {
        // Because we're rounding the width of each cell the cells don't cover the space completly, so we're making the first cell a few pixels wider to make sure we fill everything
        width = screenWidth - CGFloat(objects.count-1)*width
    }
    return CGSize(width: width, height: collectionView.bounds.height)
}