我有一个带有流布局的 UICollectionView,每个单元格都是一个正方形。如何确定每行中每个单元格之间的间距?我似乎找不到合适的设置。我看到集合视图的 nib 文件上有一个最小间距属性,但我将其设置为 0 并且单元格甚至不粘在一起。
还有其他想法吗?
更新:这个答案的 Swift 版本:https://github.com/fanpyi/UICollectionViewLeftAlignedLayout-Swift https://github.com/fanpyi/UICollectionViewLeftAlignedLayout-Swift
Taking @matt 的领导 https://stackoverflow.com/a/13258495/250190我修改了他的代码以确保项目始终左对齐。我发现,如果一个项目本身位于一行,它将以流布局为中心。我做了以下更改来解决这个问题。
仅当单元格宽度不同时才会发生这种情况,这可能会导致如下所示的布局。由于以下行为,最后一行始终左对齐UICollectionViewFlowLayout
,问题在于除最后一项之外的任何行中单独存在的项目。
通过@matt的代码我看到了。
在该示例中,我们看到如果单元格最终单独在线上,则单元格会居中。下面的代码确保您的集合视图看起来像这样。
#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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)