我如何在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;
我有问题与接受的答案,所以我更新了它,这是为我工作:
.h
@interface MaxSpacingCollectionViewFlowLayout : UICollectionViewFlowLayout
@property (nonatomic,assign) CGFloat maxCellSpacing;
@end
.m
@implementation MaxSpacingCollectionViewFlowLayout
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
if (attributes.count <= 0) return attributes;
CGFloat firstCellOriginX = ((UICollectionViewLayoutAttributes *)attributes[0]).frame.origin.x;
for(int i = 1; i < attributes.count; i++) {
UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
if (currentLayoutAttributes.frame.origin.x == firstCellOriginX) { // The first cell of a new row
continue;
}
UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
CGFloat prevOriginMaxX = CGRectGetMaxX(prevLayoutAttributes.frame);
if ((currentLayoutAttributes.frame.origin.x - prevOriginMaxX) > self.maxCellSpacing) {
CGRect frame = currentLayoutAttributes.frame;
frame.origin.x = prevOriginMaxX + self.maxCellSpacing;
currentLayoutAttributes.frame = frame;
}
}
return attributes;
}
@end
我使用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;