iOS – UICollectionView在设置为0后仍然在单元格之间有间距

在将所有内容设置为0时,我在单元格之间获得了小空格。我在cellForItemAtIndexPath就是为每个单元格设置backgroundColor

这是我的代码:

 //collectionView frame _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150) collectionViewLayout:layout]; ... - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { //The cell sizes are divided by the width of the collectionView. return CGSizeMake(_collectionView.frame.size.width/12, _collectionView.frame.size.width/12); } - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { return UIEdgeInsetsMake(0, 0, 0, 0); } - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { return 0.0f; } - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section { return 0.0f; } 

我的集合视图看起来像这样。 您会看到某些单元格之间存在黑线。 是什么造成的? 我怎样才能删除这些线?

在此处输入图像描述

任何帮助是极大的赞赏。 提前致谢。

我也遇到了这个问题。 感谢@tenric指出并且对我来说是因为宽度不能被所需列的数量整除。 我的解决方案如下:

 var itemWidth: CGFloat { get { return floor(view.frame.size.width / 7) } } 

因为我正在使用AutoLayout,我只是将间隙调整到collectionView的宽度,如下所示(请参阅widthAnchor):

 collectionView?.topAnchor.constraint(equalTo: headerSeparator.bottomAnchor).isActive = true collectionView?.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true collectionView?.bottomAnchor.constraint(equalTo: footerSeparator.topAnchor).isActive = true let gap = view.frame.size.width - (itemWidth * 7) collectionViewWidthConstraint = collectionView?.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -gap) 

因为宽度和高度都不能被12整除,所以它会保留一些空的像素点。为避免这种情况,collectionView的宽度和高度都应该是12的倍数。

我也为此疯狂。 我想要一个通用的解决方案,因为我的iPhone每行有3个单元,iPad每行有4个单元,而UICollectionView覆盖了整个屏幕宽度,所有设备的宽度都不同。

我最终通过使用ceil(frame.width / itemsPerRow)使单元格的组合宽度比设备屏幕更宽。 然后,我计算了一行中单元格的总宽度,并与屏幕宽度(view.frame)进行比较,以获得单元格将创建的宽度溢出。 知道溢出我将UICollectionView的尾随约束设置为负溢出。 这意味着UICollectionView实际上会以大约一个像素溢出屏幕宽度,但在我的情况下,这不是问题。 希望下面的代码有助于澄清并让您了解如何解决这个问题。

 // calculating cell width let frame = view.frame let cellWidth = ceil(frame.width / itemsPerRow) // adjust UICollectionView to avoid space between cells let totalCellsWidth = cellWidth * itemsPerRow let overflow = totalCellsWidth - frame.width let adjustedConstraint = -overflow collectionViewsTrailingConstraint.constant = adjustedConstraint