Skip to content

Commit 91fea6d

Browse files
alexookahAlexandros Lykesas
andauthored
Handle minimum & maximum items to scroll for default newTargetOffset (#72)
Co-authored-by: Alexandros Lykesas <[email protected]>
1 parent 96bc95e commit 91fea6d

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

Sources/MSPeekCollectionViewDelegateImplementation/MSCollectionViewPaging.swift

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,20 @@ public class MSCollectionViewPaging: NSObject {
5252
currentContentOffset = dataSource?.collectionViewPaging(self, offsetForItemAtIndex: index) ?? 0
5353
}
5454

55+
func getIndexWithMinimumAndMaximumItemsToScroll(currentIndex: Int) -> Int {
56+
var offset = currentIndex
57+
// If we've set a minimum number of items to scroll, enforce it
58+
if let minimumItemsToScroll = dataSource?.collectionViewPagingMinimumItemsToScroll(self), offset != 0 {
59+
offset = max(offset, minimumItemsToScroll)
60+
}
61+
62+
// If we've set a maximum number of items to scroll, enforce it
63+
if let maximumItemsToScroll = dataSource?.collectionViewPagingMaximumItemsToScroll(self) {
64+
offset = min(offset, maximumItemsToScroll)
65+
}
66+
return offset
67+
}
68+
5569
func getNewTargetOffset(startingOffset: CGFloat, velocity: CGFloat, targetOffset: CGFloat) -> CGFloat {
5670

5771
// Check the velocity, if it's greater than the threshold, move at least 1 cell in the direction of the velocity
@@ -71,15 +85,7 @@ public class MSCollectionViewPaging: NSObject {
7185
// Making sure we move at least 1 cell
7286
var offset = max(targetIndex - currentIndex, 1)
7387

74-
// If we've set a minimum number of items to scroll, enforce it
75-
if let minimumItemsToScroll = dataSource?.collectionViewPagingMinimumItemsToScroll(self), offset != 0 {
76-
offset = max(offset, minimumItemsToScroll)
77-
}
78-
79-
// If we've set a maximum number of items to scroll, enforce it
80-
if let maximumItemsToScroll = dataSource?.collectionViewPagingMaximumItemsToScroll(self) {
81-
offset = min(offset, maximumItemsToScroll)
82-
}
88+
offset = getIndexWithMinimumAndMaximumItemsToScroll(currentIndex: offset)
8389

8490
// The final index is the current index ofsetted by the value and in the velocity direction
8591
var finalIndex = currentIndex + (offset * Sign(value: velocity).multiplier)
@@ -93,7 +99,10 @@ public class MSCollectionViewPaging: NSObject {
9399

94100
default:
95101

96-
let finalIndex = dataSource?.collectionViewPaging(self, indexForItemAtOffset: targetOffset) ?? 0
102+
var finalIndex = dataSource?.collectionViewPaging(self, indexForItemAtOffset: targetOffset) ?? 0
103+
104+
finalIndex = getIndexWithMinimumAndMaximumItemsToScroll(currentIndex: finalIndex)
105+
97106
return dataSource?.collectionViewPaging(self, offsetForItemAtIndex: finalIndex) ?? 0
98107
}
99108
}

0 commit comments

Comments
 (0)