美文网首页
设置瀑布流距左间隔一样

设置瀑布流距左间隔一样

作者: 梁苏珍 | 来源:发表于2017-12-15 09:59 被阅读0次

照着下面的步骤,添加 代理方法 和.h.m方法,就可以实现下图的效果

添加的代理 EqualSpaceFlowLayoutDelegate

EqualSpaceFlowLayout *flowLayout = [[EqualSpaceFlowLayout alloc] init];

flowLayout.delegate = self;

新建EqualSpaceFlowLayoutDelegate  下面是.h代码

#import@protocol EqualSpaceFlowLayoutDelegate@end@interface EqualSpaceFlowLayout : UICollectionViewFlowLayout@property (nonatomic,weak) iddelegate;

@end

新建EqualSpaceFlowLayoutDelegate  下面是.m代码

#import "EqualSpaceFlowLayout.h"

@interface EqualSpaceFlowLayout()

@property (nonatomic, strong) NSMutableArray *itemAttributes;

@end

@implementation EqualSpaceFlowLayout

- (id)init

{

if (self = [super init]) {

self.scrollDirection = UICollectionViewScrollDirectionVertical;

self.minimumInteritemSpacing = 10;

self.minimumLineSpacing = 10;

self.sectionInset = UIEdgeInsetsMake(20, 15, 15, 15);

}

return self;

}

#pragma mark - Methods to Override

- (void)prepareLayout

{

[super prepareLayout];

NSInteger itemCount = [[self collectionView] numberOfItemsInSection:0];

self.itemAttributes = [NSMutableArray arrayWithCapacity:itemCount];

CGFloat xOffset = self.sectionInset.left;

CGFloat yOffset = self.sectionInset.top;

CGFloat xNextOffset = self.sectionInset.left;

for (NSInteger idx = 0; idx < itemCount; idx++) {

NSIndexPath *indexPath = [NSIndexPath indexPathForItem:idx inSection:0];

CGSize itemSize = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];

xNextOffset+=(self.minimumInteritemSpacing + itemSize.width);

if (xNextOffset > [self collectionView].bounds.size.width - self.sectionInset.right) {

xOffset = self.sectionInset.left;

xNextOffset = (self.sectionInset.left + self.minimumInteritemSpacing + itemSize.width);

yOffset += (itemSize.height + self.minimumLineSpacing);

}

else

{

xOffset = xNextOffset - (self.minimumInteritemSpacing + itemSize.width);

}

UICollectionViewLayoutAttributes *layoutAttributes =

[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

layoutAttributes.frame = CGRectMake(xOffset, yOffset, itemSize.width, itemSize.height);

[_itemAttributes addObject:layoutAttributes];

}

}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath

{

return (self.itemAttributes)[indexPath.item];

}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

{

return [self.itemAttributes filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UICollectionViewLayoutAttributes *evaluatedObject, NSDictionary *bindings) {

return CGRectIntersectsRect(rect, [evaluatedObject frame]);

}]];

}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds

{

return NO;

}

@end

相关文章

网友评论

      本文标题:设置瀑布流距左间隔一样

      本文链接:https://www.haomeiwen.com/subject/voerwxtx.html