【问题标题】:Reduce interitem spacing in UICollectionView减少 UICollectionView 中的项目间距
【发布时间】:2017-01-17 12:35:43
【问题描述】:

我已经查过了:-

UICollectionView distance between cells?

Cell spacing in UICollectionView

Decrease Space between UICollectionViewCells

但没有一个对我有用。

我也尝试过实现 UICollectionViewDelegateFlowLayout 并实现了

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 3
}

但对它没有影响。

请看以下 iPhone 7 / iPhone 5s / iPhone 7 Plus 截图(图片顺序相同)

我还查看了自调整大小的单元格,但我不想要自调整大小的单元格,因为我的项目大小始终是固定的并且符合我的要求。

我还在情节提要中设置了单元格的最小间距,但它对布局没有影响。

如何减少两个单元格之间的大间隙(项目间距),避免在 iPhone 5S 中剪切以及在 iPhone 7 Plus 中右侧的空白区域(由于背景,您看不到是白色的)

我们将不胜感激。

【问题讨论】:

标签: ios iphone swift uicollectionview uicollectionviewlayout


【解决方案1】:

如果您的单元格大小是 "Fixed" ,则无法避免间隙,因为您已硬编码固定宽度!

您需要计算 collectionView.frame 的总宽度并将其除以 2,还包括项目之间的间距,而不是“固定”大小。快速输入示例:

(计算单元格大小)

CGFloat spacing = 3.0f
CGFloat itemWidth = collectionView.frame.size.width / 2 - spacing
CGSize totalSize = itemWidth, itemWidth

【讨论】:

  • 我会试试这个并回复你。谢谢,答案似乎非常合乎逻辑。
  • @DarkInnocence Np,我强烈建议您在截屏时对单元格视图使用自动布局,因此如果您的屏幕较小/较大,您将始终保持设计完美。
  • 像魅力一样工作:D!非常感谢。顺便说一句,自动布局已经实现。
  • @DarkInnocence 太棒了! :)
【解决方案2】:

尝试在sizeForItemAtIndexPath方法中设置每个单元格的widthheight

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    float cellWidth = screenWidth / 2.0; //Replace the divisor with the column count requirement. Make sure to have it in float.

    CGFloat screenHeight = screenRect.size.height;
    screenHeight = screenHeight - 114.0; // Sum of Bottom View & Top View Height

    float cellHeight = screenHeight /(totalArray.count/2);  //totalArray contains item used to show in collectionview

    if(DEFAULT_CELL_HEIGHT > cellHeight){
        cellHeight=DEFAULT_CELL_HEIGHT;
    }

    CGSize size = CGSizeMake(cellWidth, cellHeight);

    return size;
}

【讨论】:

    【解决方案3】:

    @Hauzin 的回答可以消除不同设备中的间距。对于单元格之间的间距(minimumInteritemSpacingForSectionAt),您是否使您的视图控制器符合此协议(UICollectionViewDelegateFlowLayout)?

    【讨论】:

    • 是的,您已经在那里实现了该方法。但我问的是您是否真的在代码中符合该协议。 MyViewController: UIViewController, UICollectionViewDelegateFlowLayout
    • 是的,我做到了。在 Hauzin 的解决方案之前,我正在计算错误的宽度(硬编码宽度)