This repository was archived by the owner on Nov 28, 2022. It is now read-only.
forked from keighl/KTCenterFlowLayout
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathANDistributedFlowLayout.m
More file actions
83 lines (60 loc) · 2.82 KB
/
ANDistributedFlowLayout.m
File metadata and controls
83 lines (60 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// ANDistributedFlowLayout.m
//
// Originally: KTCenterFlowLayout.m
// Created by Kyle Truscott on 10/9/14.
// Copyright (c) 2014 keighl. All rights reserved.
//
// Modified by Andrew Naylor on 30/07/14
//
#import "ANDistributedFlowLayout.h"
@implementation ANDistributedFlowLayout
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray *superAttributes = [NSMutableArray arrayWithArray:[super layoutAttributesForElementsInRect:rect]];
NSMutableDictionary *rowCollections = [NSMutableDictionary new];
// Collect attributes by their midY coordinate.. i.e. rows!
for (UICollectionViewLayoutAttributes *itemAttributes in superAttributes)
{
// Normalize the midY to others in the row
// with variable cell heights the midYs can be ever so slightly
// different.
CGFloat midYRound = roundf(CGRectGetMidY(itemAttributes.frame));
CGFloat midYPlus = midYRound + 1;
CGFloat midYMinus = midYRound - 1;
NSNumber *key;
if (rowCollections[@(midYPlus)])
key = @(midYPlus);
if (rowCollections[@(midYMinus)])
key = @(midYMinus);
if (!key)
key = @(midYRound);
if (!rowCollections[key])
rowCollections[key] = [NSMutableArray new];
[(NSMutableArray *) rowCollections[key] addObject:itemAttributes];
}
CGFloat collectionViewWidth = CGRectGetWidth(self.collectionView.bounds) - self.collectionView.contentInset.left - self.collectionView.contentInset.right;
// Adjust the items in each row
[rowCollections enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSArray *itemAttributesCollection = obj;
NSInteger itemsInRow = [itemAttributesCollection count];
// Sum the width of all elements in the row
CGFloat aggregateItemWidths = 0.f;
for (UICollectionViewLayoutAttributes *itemAttributes in itemAttributesCollection)
aggregateItemWidths += CGRectGetWidth(itemAttributes.frame);
// |-x-x-x-x-| ... calculate the total space left
CGFloat aggregateInteritemSpacing = collectionViewWidth - aggregateItemWidths;
CGFloat interItemSpacing = aggregateInteritemSpacing / (itemsInRow + 1);
// Adjust each item's position to be centered
CGRect previousFrame = CGRectZero;
for (UICollectionViewLayoutAttributes *itemAttributes in itemAttributesCollection)
{
CGRect itemFrame = itemAttributes.frame;
itemFrame.origin.x = CGRectGetMaxX(previousFrame) + interItemSpacing;
itemAttributes.frame = itemFrame;
previousFrame = itemFrame;
}
}];
return superAttributes;
}
@end