我有一个带有流动布局的UICollectionView,每个单元都是正方形.如何确定每行上每个单元格之间的间距?我似乎找不到合适的设置.我看到集合视图的nib文件上有一个最小间距属性,但我将其设置为0,单元格甚至不会粘住.
还有其他 idea 吗?
我有一个带有流动布局的UICollectionView,每个单元都是正方形.如何确定每行上每个单元格之间的间距?我似乎找不到合适的设置.我看到集合视图的nib文件上有一个最小间距属性,但我将其设置为0,单元格甚至不会粘住.
还有其他 idea 吗?
更新:此答案的Swift版本:https://github.com/fanpyi/UICollectionViewLeftAlignedLayout-Swift
取@matt's lead,我修改了他的代码,以确保项目始终保持左对齐.我发现,如果一个项目单独结束在一条线上,它会被流程布局居中.为了解决这个问题,我做了以下修改.
只有当单元格的宽度不同时,才会出现这种情况,这可能会导致如下布局.由于UICollectionViewFlowLayout
的行为,最后一行总是左对齐,问题在于除了最后一行之外的任何一行中的项目本身.
我看到了@matt的代码.
在这个例子中,我们看到,如果细胞自己最终在直线上,它们就会居中.下面的代码确保你的Collection 视图是这样的.
#import "CWDLeftAlignedCollectionViewFlowLayout.h"
const NSInteger kMaxCellSpacing = 9;
@implementation CWDLeftAlignedCollectionViewFlowLayout
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes* attributes in attributesToReturn) {
if (nil == attributes.representedElementKind) {
NSIndexPath* indexPath = attributes.indexPath;
attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
}
}
return attributesToReturn;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewLayoutAttributes* currentItemAttributes =
[super layoutAttributesForItemAtIndexPath:indexPath];
UIEdgeInsets sectionInset = [(UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout sectionInset];
CGRect currentFrame = currentItemAttributes.frame;
if (indexPath.item == 0) { // first item of section
currentFrame.origin.x = sectionInset.left; // first item of the section should always be left aligned
currentItemAttributes.frame = currentFrame;
return currentItemAttributes;
}
NSIndexPath* previousIndexPath = [NSIndexPath indexPathForItem:indexPath.item-1 inSection:indexPath.section];
CGRect previousFrame = [self layoutAttributesForItemAtIndexPath:previousIndexPath].frame;
CGFloat previousFrameRightPoint = CGRectGetMaxX(previousFrame) + kMaxCellSpacing;
CGRect strecthedCurrentFrame = CGRectMake(0,
currentFrame.origin.y,
self.collectionView.frame.size.width,
currentFrame.size.height);
if (!CGRectIntersectsRect(previousFrame, strecthedCurrentFrame)) { // if current item is the first item on the line
// the approach here is to take the current frame, left align it to the edge of the view
// then stretch it the width of the collection view, if it intersects with the previous frame then that means it
// is on the same line, otherwise it is on it's own new line
currentFrame.origin.x = sectionInset.left; // first item on the line should always be left aligned
currentItemAttributes.frame = currentFrame;
return currentItemAttributes;
}
currentFrame.origin.x = previousFrameRightPoint;
currentItemAttributes.frame = currentFrame;
return currentItemAttributes;
}
@end