forked from ecerney/CollectionViewWaterfallLayout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollectionViewWaterfallLayout.swift
342 lines (268 loc) · 12.9 KB
/
CollectionViewWaterfallLayout.swift
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
//
// CollectionViewWaterfallLayout.swift
// CollectionViewWaterfallLayout
//
// Created by Eric Cerney on 7/21/14.
// Based on CHTCollectionViewWaterfallLayout by Nelson Tai
// Copyright (c) 2014 Eric Cerney. All rights reserved.
//
import UIKit
@objc public protocol CollectionViewWaterfallLayoutDelegate: UICollectionViewDelegateFlowLayout {
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, numberOfColumnsInSection section: Int) -> Int
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, insetForHeaderInSection section: Int) -> UIEdgeInsets
@objc optional func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, insetForFooterInSection section: Int) -> UIEdgeInsets
}
public class CollectionViewWaterfallLayout: UICollectionViewLayout {
// MARK: - Private constants
/// How many items to be union into a single rectangle
private let unionSize = 20
// MARK: - Public Properties
public var columnCount: Int = 2 {
didSet {
invalidateIfNotEqual(oldValue, newValue: columnCount)
}
}
public var minimumColumnSpacing: CGFloat = 10.0 {
didSet {
invalidateIfNotEqual(oldValue, newValue: minimumColumnSpacing)
}
}
public var minimumInteritemSpacing: CGFloat = 10.0 {
didSet {
invalidateIfNotEqual(oldValue, newValue: minimumInteritemSpacing)
}
}
public var headerHeight: CGFloat = 0.0 {
didSet {
invalidateIfNotEqual(oldValue, newValue: headerHeight)
}
}
public var footerHeight: CGFloat = 0.0 {
didSet {
invalidateIfNotEqual(oldValue, newValue: footerHeight)
}
}
public var headerInset: UIEdgeInsets = .zero {
didSet {
invalidateIfNotEqual(oldValue, newValue: headerInset)
}
}
public var footerInset: UIEdgeInsets = .zero {
didSet {
invalidateIfNotEqual(oldValue, newValue: footerInset)
}
}
public var sectionInset: UIEdgeInsets = .zero {
didSet {
invalidateIfNotEqual(oldValue, newValue: sectionInset)
}
}
public override var collectionViewContentSize: CGSize {
let numberOfSections = collectionView?.numberOfSections
if numberOfSections == 0 {
return .zero
}
var contentSize = collectionView?.bounds.size
contentSize?.height = collectionViewContentSizeHeight
return contentSize!
}
// MARK: - Private Properties
private weak var delegate: CollectionViewWaterfallLayoutDelegate? {
get {
return collectionView?.delegate as? CollectionViewWaterfallLayoutDelegate
}
}
// private var columnHeights = [CGFloat]()
private var collectionViewContentSizeHeight: CGFloat = 0
private var sectionItemAttributes = [[UICollectionViewLayoutAttributes]]()
private var allItemAttributes = [UICollectionViewLayoutAttributes]()
private var headersAttribute = [Int: UICollectionViewLayoutAttributes]()
private var footersAttribute = [Int: UICollectionViewLayoutAttributes]()
private var unionRects = [CGRect]()
// MARK: - UICollectionViewLayout Methods
public override func prepare() {
super.prepare()
guard let numberOfSections = collectionView?.numberOfSections else {
return
}
guard let delegate = delegate else {
assertionFailure("UICollectionView's delegate should conform to CollectionViewWaterfallLayoutDelegate protocol")
return
}
guard let collectionView = collectionView else {
return
}
assert(columnCount > 0, "CollectionViewWaterfallLayout's columnCount should be greater than 0")
// Initialize variables
headersAttribute.removeAll(keepingCapacity: false)
footersAttribute.removeAll(keepingCapacity: false)
unionRects.removeAll(keepingCapacity: false)
allItemAttributes.removeAll(keepingCapacity: false)
sectionItemAttributes.removeAll(keepingCapacity: false)
collectionViewContentSizeHeight = 0
// Create attributes
var top: CGFloat = 0
var attributes: UICollectionViewLayoutAttributes
for section in 0..<numberOfSections {
let columnCount = delegate.collectionView?(collectionView, layout: self, numberOfColumnsInSection: section) ?? self.columnCount
var columnHeights = Array(repeating: top, count: columnCount)
/*
* 1. Get section-specific metrics (minimumInteritemSpacing, sectionInset)
*/
let minimumInteritemSpacing = delegate.collectionView?(collectionView, layout: self, minimumInteritemSpacingForSectionAt: section) ?? self.minimumInteritemSpacing
let sectionInset = delegate.collectionView?(collectionView, layout: self, insetForSectionAt: section) ?? self.sectionInset
let contentWidth = collectionView.bounds.size.width - collectionView.contentInset.left - collectionView.contentInset.right
let width = contentWidth - sectionInset.left - sectionInset.right
let itemWidth = floor((width - CGFloat(columnCount - 1) * CGFloat(minimumColumnSpacing)) / CGFloat(columnCount))
/*
* 2. Section header
*/
let headerHeight = delegate.collectionView?(collectionView, layout: self, referenceSizeForHeaderInSection: section).height ?? self.headerHeight
let headerInset = delegate.collectionView?(collectionView, layout: self, insetForHeaderInSection: section) ?? self.headerInset
top += headerInset.top
if headerHeight > 0 {
attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
with: IndexPath(item: 0, section: section))
attributes.frame = CGRect(x: headerInset.left, y: top, width: contentWidth - (headerInset.left + headerInset.right), height: headerHeight)
headersAttribute[section] = attributes
allItemAttributes.append(attributes)
top = attributes.frame.maxY + headerInset.bottom
}
top += sectionInset.top
for idx in 0..<columnCount {
columnHeights[idx] = top
}
/*
* 3. Section items
*/
let itemCount = collectionView.numberOfItems(inSection: section)
var itemAttributes = [UICollectionViewLayoutAttributes]()
// Item will be put into shortest column.
for idx in 0..<itemCount {
let indexPath = IndexPath(item: idx, section: section)
let columnIndex = shortestColumnIndex(in: columnHeights)
let xOffset = CGFloat(sectionInset.left) + CGFloat(itemWidth + minimumColumnSpacing) * CGFloat(columnIndex)
let yOffset = columnHeights[columnIndex]
let itemSize = delegate.collectionView?(collectionView, layout: self, sizeForItemAt: indexPath) ?? .zero
var itemHeight: CGFloat = 0.0
if itemSize.height > 0 && itemSize.width > 0 {
itemHeight = itemSize.height * itemWidth / itemSize.width
}
attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(x: xOffset, y: yOffset, width: itemWidth, height: itemHeight)
itemAttributes.append(attributes)
allItemAttributes.append(attributes)
columnHeights[columnIndex] = attributes.frame.maxY + minimumInteritemSpacing
}
sectionItemAttributes.append(itemAttributes)
/*
* 4. Section footer
*/
let columnIndex = longestColumnIndex(in: columnHeights)
top = columnHeights[columnIndex] - minimumInteritemSpacing + sectionInset.bottom
let footerHeight = delegate.collectionView?(collectionView, layout: self, referenceSizeForFooterInSection: section).height ?? self.footerHeight
let footerInset: UIEdgeInsets = delegate.collectionView?(collectionView, layout: self, insetForFooterInSection: section) ?? self.footerInset
top += footerInset.top
if footerHeight > 0 {
attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
with: IndexPath(item: 0, section: section))
attributes.frame = CGRect(x: footerInset.left, y: CGFloat(top), width: contentWidth - (footerInset.left + footerInset.right), height: CGFloat(footerHeight))
footersAttribute[section] = attributes
allItemAttributes.append(attributes)
top = attributes.frame.maxY + footerInset.bottom
}
}
collectionViewContentSizeHeight = top
// Build union rects
var idx = 0
let itemCounts = allItemAttributes.count
while idx < itemCounts {
let rect1 = allItemAttributes[idx].frame
idx = min(idx + unionSize, itemCounts) - 1
let rect2 = allItemAttributes[idx].frame
unionRects.append(rect1.union(rect2))
idx += 1
}
}
public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if indexPath.section >= sectionItemAttributes.count {
return nil
}
if indexPath.item >= sectionItemAttributes[indexPath.section].count {
return nil
}
return sectionItemAttributes[indexPath.section][indexPath.item]
}
public override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
var attribute: UICollectionViewLayoutAttributes?
switch elementKind {
case UICollectionView.elementKindSectionHeader:
attribute = headersAttribute[indexPath.section]
case UICollectionView.elementKindSectionFooter:
attribute = footersAttribute[indexPath.section]
default: break
}
return attribute
}
public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var begin: Int = 0
var end: Int = unionRects.count
var attrs = [UICollectionViewLayoutAttributes]()
for i in 0..<unionRects.count {
if rect.intersects(unionRects[i]) {
begin = i * unionSize
break
}
}
for i in (0..<unionRects.count).reversed() {
if rect.intersects(unionRects[i]) {
end = min((i+1) * unionSize, allItemAttributes.count)
break
}
}
for i in begin..<end {
let attr = allItemAttributes[i]
if rect.intersects(attr.frame) {
attrs.append(attr)
}
}
return Array(attrs)
}
public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
let oldBounds = collectionView?.bounds
if newBounds.width != oldBounds?.width {
return true
}
return false
}
}
// MARK: - Private Methods
private extension CollectionViewWaterfallLayout {
func shortestColumnIndex(in columnHeights: [CGFloat]) -> Int {
var index: Int = 0
var shortestHeight: CGFloat = CGFloat(MAXFLOAT)
for (idx, height) in columnHeights.enumerated() {
if height < shortestHeight {
shortestHeight = height
index = idx
}
}
return index
}
func longestColumnIndex(in columnHeights: [CGFloat]) -> Int {
var index: Int = 0
var longestHeight: CGFloat = 0
for (idx, height) in columnHeights.enumerated() {
if height > longestHeight {
longestHeight = height
index = idx
}
}
return index
}
func invalidateIfNotEqual<T: Equatable>(_ oldValue: T, newValue: T) {
if oldValue != newValue {
invalidateLayout()
}
}
}