Skip to content
This repository was archived by the owner on Jun 17, 2023. It is now read-only.

Commit d5ab697

Browse files
author
grant
committed
optimize layout calculation
2 parents a72d426 + abc6604 commit d5ab697

File tree

1 file changed

+14
-22
lines changed

1 file changed

+14
-22
lines changed

Lib/CollectionViewPagingLayout.swift

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,9 @@ public class CollectionViewPagingLayout: UICollectionViewLayout {
4343
}
4444

4545
private var numberOfItems: Int {
46-
var count = 0
47-
if let sectionCount = collectionView?.numberOfSections {
48-
for i in (0 ..< sectionCount) {
49-
count += collectionView?.numberOfItems(inSection: i) ?? 0
50-
}
51-
}
52-
return count
46+
return (0..<(collectionView?.numberOfSections ?? 0))
47+
.compactMap { collectionView?.numberOfItems(inSection: $0) }
48+
.reduce(0, +)
5349
}
5450

5551

@@ -94,23 +90,19 @@ public class CollectionViewPagingLayout: UICollectionViewLayout {
9490
let endIndex = min(numberOfItems, initialEndIndex + startIndexOutOfBounds)
9591

9692
var attributesArray: [UICollectionViewLayoutAttributes] = []
97-
let sectionCount = collectionView?.numberOfSections ?? 0
93+
var section = 0
94+
var numberOfItemsInSection = collectionView?.numberOfItems(inSection: section) ?? 0
95+
var numberOfItemsInPrevSections = 0
9896
for index in startIndex..<endIndex {
99-
var section = 0
100-
var row = 0
101-
var accIndex = 0
102-
for i in (0 ..< sectionCount) {
103-
if index - accIndex < collectionView!.numberOfItems(inSection: i) {
104-
section = i
105-
row = index - accIndex
106-
break;
107-
}
108-
else{
109-
accIndex += collectionView!.numberOfItems(inSection: i)
110-
}
97+
var item = index - numberOfItemsInPrevSections
98+
while item >= numberOfItemsInSection {
99+
numberOfItemsInPrevSections += numberOfItemsInSection
100+
section += 1
101+
numberOfItemsInSection = collectionView?.numberOfItems(inSection: section) ?? 0
102+
item = index - numberOfItemsInPrevSections
111103
}
112-
113-
let cellAttributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(row: row, section: section))
104+
105+
let cellAttributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: item, section: section))
114106
let pageIndex = CGFloat(index)
115107
let progress = pageIndex - currentScrollOffset
116108
var zIndex = Int(-abs(round(progress)))

0 commit comments

Comments
 (0)