【问题标题】:UICollectionView with zero cell spacing单元格间距为零的 UICollectionView
【发布时间】:2016-10-25 05:12:41
【问题描述】:

我已关注this answer 并尝试每行实现 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

【问题讨论】:

  • 看起来那些是图像。他们是吗?储物柜#1000?
  • layout.itemSize = CGSize(width: itemWidth, height: itemWidth) 这是控制您的项目大小。尝试使用 screenWidth/5 作为 itemWidth
  • @MNM 这是一个 UILabel。是的,我尝试输入layout.itemSize = CGSize(width: screenWidth/5, height: screenWidth/5) ,但没有运气:(
  • 尝试将其放入容器视图并将背景涂成黑色
  • 你必须在模拟器上运行它。在设备上尝试一下,我认为您不会看到这些线条。

标签: ios iphone uicollectionview swift3 uicollectionviewlayout


【解决方案1】:

必须是

let itemWidth : CGFloat = (screenWidth / 5.0)

所以结果不会四舍五入。

更新

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

更新 2

如果您使用情节提要,则无需创建UICollectionViewFlowLayout。您可以从情节提要中设置插图和间距。 然后在你的 .m 文件中实现这个来确定项目的大小。

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

【讨论】:

  • 谢谢,但它没有帮助:(同样的场景。
  • collectionview 正在使用情节提要,并且自动布局设置为 4 个方向。
  • 感谢您的宝贵时间 :)
【解决方案2】:

要修复空格,每个单元格的大小应为整数。那么四舍五入之和与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)
}

【讨论】:

    猜你喜欢
    • 2013-06-18
    • 2015-05-01
    • 1970-01-01
    • 2013-03-09
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多