Skip to content

Commit b2d84f9

Browse files
committed
Improving the perf by using the cache effectively
1 parent 3f38187 commit b2d84f9

1 file changed

Lines changed: 25 additions & 13 deletions

File tree

Sources/CollectionViewSlantedLayout.swift

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,7 @@ import UIKit
4040
*/
4141
@IBInspectable open var slantingSize: UInt = 75 {
4242
didSet {
43-
updateRotationAngle()
44-
invalidateLayout()
43+
invalidate()
4544
}
4645
}
4746

@@ -52,8 +51,7 @@ import UIKit
5251
*/
5352
@objc open var slantingDirection: SlantingDirection = .upward {
5453
didSet {
55-
updateRotationAngle()
56-
invalidateLayout()
54+
invalidate()
5755
}
5856
}
5957

@@ -79,8 +77,7 @@ import UIKit
7977
*/
8078
@objc open var scrollDirection: UICollectionView.ScrollDirection = .vertical {
8179
didSet {
82-
updateRotationAngle()
83-
invalidateLayout()
80+
invalidate()
8481
}
8582
}
8683

@@ -91,7 +88,7 @@ import UIKit
9188
*/
9289
@IBInspectable open var isFirstCellExcluded: Bool = false {
9390
didSet {
94-
invalidateLayout()
91+
invalidate()
9592
}
9693
}
9794

@@ -113,7 +110,7 @@ import UIKit
113110
*/
114111
@IBInspectable open var isLastCellExcluded: Bool = false {
115112
didSet {
116-
invalidateLayout()
113+
invalidate()
117114
}
118115
}
119116

@@ -124,7 +121,7 @@ import UIKit
124121
*/
125122
@IBInspectable open var lineSpacing: CGFloat = 10 {
126123
didSet {
127-
invalidateLayout()
124+
invalidate()
128125
}
129126
}
130127

@@ -138,7 +135,7 @@ import UIKit
138135
*/
139136
@IBInspectable open var itemSize: CGFloat = 225 {
140137
didSet {
141-
invalidateLayout()
138+
invalidate()
142139
}
143140
}
144141

@@ -149,7 +146,7 @@ import UIKit
149146
*/
150147
@objc open var zIndexOrder: ZIndexOrder = .ascending {
151148
didSet {
152-
invalidateLayout()
149+
invalidate()
153150
}
154151
}
155152

@@ -237,6 +234,18 @@ import UIKit
237234
let angle = atan(tan(oppositeSide / adjacentSide))
238235
slantingAngle = angle * CGFloat(factor)
239236
}
237+
238+
/// :nodoc:
239+
fileprivate func invalidate() {
240+
invalidateCache()
241+
invalidateLayout()
242+
}
243+
244+
/// :nodoc:
245+
fileprivate func invalidateCache() {
246+
cachedAttributes = [CollectionViewSlantedLayoutAttributes]()
247+
cachedContentSize = 0
248+
}
240249
}
241250

242251
// MARK: CollectionViewLayout methods overriding
@@ -253,14 +262,17 @@ extension CollectionViewSlantedLayout {
253262

254263
/// :nodoc:
255264
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
265+
invalidateCache()
256266
return true
257267
}
258268

259269
/// :nodoc:
260270
override open func prepare() {
271+
guard cachedAttributes.isEmpty else {
272+
return
273+
}
274+
261275
updateRotationAngle()
262-
cachedAttributes = [CollectionViewSlantedLayoutAttributes]()
263-
cachedContentSize = 0
264276

265277
var position: CGFloat = 0
266278

0 commit comments

Comments
 (0)