我如何在UICollectionView的一个部分设置单元格间距?我知道有一个属性minimumInteritemSpacing,我已经将它设置为5.0,但间距仍然没有出现5.0。我已经实现了flowout委托方法。
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 5.0;
}
我仍然没有得到想要的结果。我认为这是最小间距。有没有什么方法可以设置最大间距?
我使用monotouch,所以名称和代码会有点不同,但你可以通过确保集合视图的宽度等于(x *单元格宽度)+ (x-1) * MinimumSpacing与x =每行单元格的数量来做到这一点。
只需要根据MinimumInteritemSpacing和Cell的宽度执行以下步骤
1)我们根据单元格大小+当前插入+最小间距计算每行项目的数量
float currentTotalWidth = CollectionView.Frame.Width - Layout.SectionInset.Left - Layout.SectionInset.Right (Layout = flowlayout)
int amountOfCellsPerRow = (currentTotalWidth + MinimumSpacing) / (cell width + MinimumSpacing)
2)现在你有了所有信息来计算集合视图的预期宽度
float totalWidth =(amountOfCellsPerRow * cell width) + (amountOfCellsPerRow-1) * MinimumSpacing
3)所以当前宽度与预期宽度之差为
float difference = currentTotalWidth - totalWidth;
4)现在调整insets(在本例中,我们将其添加到右侧,因此集合视图的左侧位置保持不变
Layout.SectionInset.Right = Layout.SectionInset.Right + difference;
我偶然发现了与op类似的问题。不幸的是,接受的答案不适合我,因为collectionView的内容不会正确居中。因此,我提出了一个不同的解决方案,只需要在collectionView中的所有项目都具有相同的宽度,这似乎是问题中的情况:
#define cellSize 90
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
float width = collectionView.frame.size.width;
float spacing = [self collectionView:collectionView layout:collectionViewLayout minimumInteritemSpacingForSectionAtIndex:section];
int numberOfCells = (width + spacing) / (cellSize + spacing);
int inset = (width + spacing - numberOfCells * (cellSize + spacing) ) / 2;
return UIEdgeInsetsMake(0, inset, 0, inset);
}
该代码将确保…minimumInteritemSpacing…将是每个collectionViewCell之间的精确间距,并进一步保证所有的单元格一起将在collectionView