ios - UICollectionViewCell 宽度大于我在 sizeForItemAt 中设置的宽度

标签 ios uicollectionview uicollectionviewcell uicollectionviewflowlayout uicollectionviewdelegate

我的 UICollectionView 的宽度/高度匹配所有可用空间。

我想在一行(两列)中显示两个单元格

所以一个单元格的宽度应该是UICollectionView的一半宽度(collectionView.frame.width/2)

所以我在 UICollectionViewDelegateFlowLayout 函数中以编程方式更改单元格的宽度:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width / 2.0, height: 150)
}

但单元格的视觉宽度比 collectionView.frame.width/2.0 大得多(在 iPhone SE 模拟器上测试)

所以它占用了超过屏幕半角的空间

这里我打印了关于尺寸的信息:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
    print("didSelectItemAt \(cell.frame.width), table width: \(collectionView.frame.width), item calc width: \(collectionView.frame.width / 2)")
}

didSelectItemAt cell width 187.5, table width: 375.0, half-width: 187.5

enter image description here

为什么会这样?

边距也有问题,但首先我必须解决这个问题

更新

虽然它在 iPhone 6s 模拟器上运行良好(我编辑图像以将两个项目放在第一行以检查它们是否适合):

enter image description here

那么 iPhone SE 有什么问题呢?

我不想发现其他 iPhone 或 iPad 也可能存在同样的问题

最佳答案

375.0 是 iPhone 6s 和 X 的尺寸,而不是 iPhone SE 的尺寸 320.0

原因是 collectionView 在 iPhone 6s 模式下设置了宽度约束,但后来切换到 SE 模拟器时,这个约束没有更新。

关于ios - UICollectionViewCell 宽度大于我在 sizeForItemAt 中设置的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55407982/

相关文章:

ios - 如何在 iOS 7 中解析这个 xml?

ios - 重新加载时 UICollectionView 闪烁问题

ios - 转换 UICollectionViewCell 导致无法捕获触摸事件

swift - 如何让细胞变大几秒钟?

ios - NSUserDefaults-保存UIImageView位置

ios - UIView 不适合整个屏幕 屏幕顶部显示白色条

ios - 使用元组 Swift 3 在单个 switch-case 中实现多个间隔

ios - 如何修复 UICollectionViewCell 中的图像高度?

ios - UITableViewCell 中的 UICollectionVIew 如何使用自动布局获取动态高度

swift - 如何在UICollectionViewCell内添加动画