-
Notifications
You must be signed in to change notification settings - Fork 5
/
CFCollectionViewLeftAlignFlowLayout.swift
74 lines (60 loc) · 2.66 KB
/
CFCollectionViewLeftAlignFlowLayout.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
//
// CFCollectionViewLeftAlignFlowLayout.swift
// CFCollectionViewLeftAlignFlowLayout
//
// Created by Code Fonsi
//
import UIKit
open class CFCollectionViewLeftAlignFlowLayout: UICollectionViewFlowLayout {
var delegate: UICollectionViewDelegateFlowLayout? {
return self.collectionView?.delegate as? UICollectionViewDelegateFlowLayout
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributesCollection = super.layoutAttributesForElements(in: rect) else {
return nil
}
var updatedAttributes = [UICollectionViewLayoutAttributes]()
attributesCollection.forEach({ (originalAttributes) in
guard originalAttributes.representedElementKind == nil else {
updatedAttributes.append(originalAttributes)
return
}
if let updatedAttribute = self.layoutAttributesForItem(at: originalAttributes.indexPath) {
updatedAttributes.append(updatedAttribute)
}
})
return updatedAttributes
}
override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let attributes = super.layoutAttributesForItem(at: indexPath)?.copy() as? UICollectionViewLayoutAttributes else {
return nil
}
guard let collectionView = self.collectionView else {
return attributes
}
let firstInSection: Bool = indexPath.item == 0
guard !firstInSection else {
let section = attributes.indexPath.section
let x = self.delegate?.collectionView?(collectionView, layout: self, insetForSectionAt: section).left ?? self.sectionInset.left
attributes.frame.origin.x = x
return attributes
}
let previousAttributes = self.layoutAttributesForItem(at: IndexPath(item: indexPath.item - 1, section: indexPath.section))
let previousFrame: CGRect = previousAttributes?.frame ?? CGRect()
let firstInRow = previousAttributes?.center.y != attributes.center.y
guard !firstInRow else {
let section = attributes.indexPath.section
let x = self.delegate?.collectionView?(collectionView, layout: self, insetForSectionAt: section).left ?? self.sectionInset.left
attributes.frame.origin.x = x
return attributes
}
let interItemSpacing: CGFloat = (collectionView.delegate as? UICollectionViewDelegateFlowLayout)?
.collectionView?(collectionView, layout: self, minimumInteritemSpacingForSectionAt: indexPath.section) ?? self.minimumInteritemSpacing
let x = previousFrame.origin.x + previousFrame.width + interItemSpacing
attributes.frame = CGRect(x: x,
y: attributes.frame.origin.y,
width: attributes.frame.width,
height: attributes.frame.height)
return attributes
}
}