forked from chiahsien/CHTCollectionViewWaterfallLayout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCHTCollectionViewWaterfallLayout.swift
executable file
·401 lines (339 loc) · 16.3 KB
/
CHTCollectionViewWaterfallLayout.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
//
// CHTCollectionViewWaterfallLayout.swift
// PinterestSwift
//
// Created by Nicholas Tau on 6/30/14.
// Copyright (c) 2014 Nicholas Tau. All rights reserved.
//
import UIKit
private func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
private func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
@objc public protocol CHTCollectionViewDelegateWaterfallLayout: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize
@objc optional func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
heightForHeaderIn section: Int) -> CGFloat
@objc optional func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
heightForFooterIn section: Int) -> CGFloat
@objc optional func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetsFor section: Int) -> UIEdgeInsets
@objc optional func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingFor section: Int) -> CGFloat
@objc optional func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
columnCountFor section: Int) -> Int
@available(*, unavailable, renamed: "collectionView(_:layout:sizeForItemAt:)")
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize
@available(*, unavailable, renamed: "collectionView(_:layout:heightForHeaderIn:)")
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
heightForHeaderInSection section: Int) -> CGFloat
@available(*, unavailable, renamed: "collectionView(_:layout:heightForFooterIn:)")
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
heightForFooterInSection section: Int) -> CGFloat
@available(*, unavailable, renamed: "collectionView(_:layout:insetsFor:)")
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int) -> UIEdgeInsets
@available(*, unavailable, renamed: "collectionView(_:layout:minimumInteritemSpacingFor:)")
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat
@available(*, unavailable, renamed: "collectionView(_:layout:columnCountFor:)")
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
columnCountForSection section: Int) -> Int
}
@available(*, unavailable, renamed: "CHTCollectionViewWaterfallLayout.ItemRenderDirection")
public enum CHTCollectionViewWaterfallLayoutItemRenderDirection { }
public extension CHTCollectionViewWaterfallLayout.ItemRenderDirection {
@available(*, unavailable, renamed: "shortestFirst")
static let chtCollectionViewWaterfallLayoutItemRenderDirectionShortestFirst = 0
@available(*, unavailable, renamed: "leftToRight")
static let chtCollectionViewWaterfallLayoutItemRenderDirectionLeftToRight = 1
@available(*, unavailable, renamed: "rightToLeft")
static let chtCollectionViewWaterfallLayoutItemRenderDirectionRightToLeft = 2
}
extension CHTCollectionViewWaterfallLayout {
public enum ItemRenderDirection: Int {
case shortestFirst
case leftToRight
case rightToLeft
}
public enum SectionInsetReference {
case fromContentInset
case fromLayoutMargins
@available(iOS 11, *)
case fromSafeArea
}
}
@available(*, unavailable, renamed: "UICollectionView.elementKindSectionHeader")
public let CHTCollectionElementKindSectionHeader = "CHTCollectionElementKindSectionHeader"
@available(*, unavailable, renamed: "UICollectionView.elementKindSectionFooter")
public let CHTCollectionElementKindSectionFooter = "CHTCollectionElementKindSectionFooter"
public class CHTCollectionViewWaterfallLayout: UICollectionViewLayout {
public var columnCount: Int = 2 {
didSet {
invalidateLayout()
}
}
public var minimumColumnSpacing: CGFloat = 10 {
didSet {
invalidateLayout()
}
}
public var minimumInteritemSpacing: CGFloat = 10 {
didSet {
invalidateLayout()
}
}
public var headerHeight: CGFloat = 0 {
didSet {
invalidateLayout()
}
}
public var footerHeight: CGFloat = 0 {
didSet {
invalidateLayout()
}
}
public var sectionInset: UIEdgeInsets = .zero {
didSet {
invalidateLayout()
}
}
public var itemRenderDirection: ItemRenderDirection = .shortestFirst {
didSet {
invalidateLayout()
}
}
public var sectionInsetReference: SectionInsetReference = .fromContentInset {
didSet {
invalidateLayout()
}
}
public var delegate: CHTCollectionViewDelegateWaterfallLayout? {
get {
return collectionView!.delegate as? CHTCollectionViewDelegateWaterfallLayout
}
}
private var columnHeights: [[CGFloat]] = []
private var sectionItemAttributes: [[UICollectionViewLayoutAttributes]] = []
private var allItemAttributes: [UICollectionViewLayoutAttributes] = []
private var headersAttributes: [Int: UICollectionViewLayoutAttributes] = [:]
private var footersAttributes: [Int: UICollectionViewLayoutAttributes] = [:]
private var unionRects: [CGRect] = []
private let unionSize = 20
private func columnCount(forSection section: Int) -> Int {
return delegate?.collectionView?(collectionView!, layout: self, columnCountFor: section) ?? columnCount
}
private var collectionViewContentWidth: CGFloat {
let insets: UIEdgeInsets
switch sectionInsetReference {
case .fromContentInset:
insets = collectionView!.contentInset
case .fromSafeArea:
if #available(iOS 11.0, *) {
insets = collectionView!.safeAreaInsets
} else {
insets = .zero
}
case .fromLayoutMargins:
insets = collectionView!.layoutMargins
}
return collectionView!.bounds.size.width - insets.left - insets.right
}
private func collectionViewContentWidth(ofSection section: Int) -> CGFloat {
let insets = delegate?.collectionView?(collectionView!, layout: self, insetsFor: section) ?? sectionInset
return collectionViewContentWidth - insets.left - insets.right
}
@available(*, unavailable, renamed: "itemWidth(inSection:)")
public func itemWidthInSectionAtIndex(_ section: Int) -> CGFloat {
return itemWidth(inSection: section)
}
public func itemWidth(inSection section: Int) -> CGFloat {
let columnCount = self.columnCount(forSection: section)
let spaceColumCount = CGFloat(columnCount - 1)
let width = collectionViewContentWidth(ofSection: section)
return floor((width - (spaceColumCount * minimumColumnSpacing)) / CGFloat(columnCount))
}
override public func prepare() {
super.prepare()
let numberOfSections = collectionView!.numberOfSections
if numberOfSections == 0 {
return
}
headersAttributes = [:]
footersAttributes = [:]
unionRects = []
allItemAttributes = []
sectionItemAttributes = []
columnHeights = (0 ..< numberOfSections).map { section in
let columnCount = self.columnCount(forSection: section)
let sectionColumnHeights = (0 ..< columnCount).map { CGFloat($0) }
return sectionColumnHeights
}
var top: CGFloat = 0.0
var attributes = UICollectionViewLayoutAttributes()
for section in 0 ..< numberOfSections {
// MARK: 1. Get section-specific metrics (minimumInteritemSpacing, sectionInset)
let minimumInteritemSpacing = delegate?.collectionView?(collectionView!, layout: self, minimumInteritemSpacingFor: section)
?? self.minimumInteritemSpacing
let sectionInsets = delegate?.collectionView?(collectionView!, layout: self, insetsFor: section) ?? self.sectionInset
let columnCount = columnHeights[section].count
let itemWidth = self.itemWidth(inSection: section)
// MARK: 2. Section header
let heightHeader = delegate?.collectionView?(collectionView!, layout: self, heightForHeaderIn: section)
?? self.headerHeight
if heightHeader > 0 {
attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: IndexPath(row: 0, section: section))
attributes.frame = CGRect(x: 0, y: top, width: collectionView!.bounds.size.width, height: heightHeader)
headersAttributes[section] = attributes
allItemAttributes.append(attributes)
top = attributes.frame.maxY
}
top += sectionInsets.top
columnHeights[section] = [CGFloat](repeating: top, count: columnCount)
// MARK: 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 = nextColumnIndexForItem(idx, inSection: section)
let xOffset = sectionInsets.left + (itemWidth + minimumColumnSpacing) * CGFloat(columnIndex)
let yOffset = columnHeights[section][columnIndex]
var itemHeight: CGFloat = 0.0
if let itemSize = delegate?.collectionView(collectionView!, layout: self, sizeForItemAt: indexPath),
itemSize.height > 0 {
itemHeight = itemSize.height
if itemSize.width > 0 {
itemHeight = floor(itemHeight * itemWidth / itemSize.width)
} // else use default item width based on other parameters
}
attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(x: xOffset, y: yOffset, width: itemWidth, height: itemHeight)
itemAttributes.append(attributes)
allItemAttributes.append(attributes)
columnHeights[section][columnIndex] = attributes.frame.maxY + minimumInteritemSpacing
}
sectionItemAttributes.append(itemAttributes)
// MARK: 4. Section footer
let columnIndex = longestColumnIndex(inSection: section)
top = columnHeights[section][columnIndex] - minimumInteritemSpacing + sectionInsets.bottom
let footerHeight = delegate?.collectionView?(collectionView!, layout: self, heightForFooterIn: section) ?? self.footerHeight
if footerHeight > 0 {
attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, with: IndexPath(item: 0, section: section))
attributes.frame = CGRect(x: 0, y: top, width: collectionView!.bounds.size.width, height: footerHeight)
footersAttributes[section] = attributes
allItemAttributes.append(attributes)
top = attributes.frame.maxY
}
columnHeights[section] = [CGFloat](repeating: top, count: columnCount)
}
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
}
}
override public var collectionViewContentSize: CGSize {
if collectionView!.numberOfSections == 0 {
return .zero
}
var contentSize = collectionView!.bounds.size
contentSize.width = collectionViewContentWidth
if let height = columnHeights.last?.first {
contentSize.height = height
return contentSize
}
return .zero
}
override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if indexPath.section >= sectionItemAttributes.count {
return nil
}
let list = sectionItemAttributes[indexPath.section]
if indexPath.item >= list.count {
return nil
}
return list[indexPath.item]
}
override public func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes {
var attribute: UICollectionViewLayoutAttributes?
if elementKind == UICollectionView.elementKindSectionHeader {
attribute = headersAttributes[indexPath.section]
} else if elementKind == UICollectionView.elementKindSectionFooter {
attribute = footersAttributes[indexPath.section]
}
return attribute ?? UICollectionViewLayoutAttributes()
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var begin = 0, end = unionRects.count
if let i = unionRects.firstIndex(where: { rect.intersects($0) }) {
begin = i * unionSize
}
if let i = unionRects.lastIndex(where: { rect.intersects($0) }) {
end = min((i + 1) * unionSize, allItemAttributes.count)
}
return allItemAttributes[begin..<end]
.filter { rect.intersects($0.frame) }
}
override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return newBounds.width != collectionView?.bounds.width
}
/// Find the shortest column.
///
/// - Returns: index for the shortest column
private func shortestColumnIndex(inSection section: Int) -> Int {
return columnHeights[section].enumerated()
.min(by: { $0.element < $1.element })?
.offset ?? 0
}
/// Find the longest column.
///
/// - Returns: index for the longest column
private func longestColumnIndex(inSection section: Int) -> Int {
return columnHeights[section].enumerated()
.max(by: { $0.element < $1.element })?
.offset ?? 0
}
/// Find the index for the next column.
///
/// - Returns: index for the next column
private func nextColumnIndexForItem(_ item: Int, inSection section: Int) -> Int {
var index = 0
let columnCount = self.columnCount(forSection: section)
switch itemRenderDirection {
case .shortestFirst :
index = shortestColumnIndex(inSection: section)
case .leftToRight :
index = item % columnCount
case .rightToLeft:
index = (columnCount - 1) - (item % columnCount)
}
return index
}
}