-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathPagingCollectionViewLayout.swift
61 lines (50 loc) · 2.04 KB
/
PagingCollectionViewLayout.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
//
// PagingCollectionViewLayout.swift
// Example
//
// Created by Alex Kerendian on 8/11/19.
// Copyright © 2019 Alexander Kerendian. All rights reserved.
//
import UIKit
class PagingCollectionViewLayout: UICollectionViewFlowLayout {
var velocityThresholdPerPage: CGFloat = 2
var numberOfItemsPerPage: CGFloat = 1
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = collectionView else { return proposedContentOffset }
let pageLength: CGFloat
let approxPage: CGFloat
let currentPage: CGFloat
let speed: CGFloat
if scrollDirection == .horizontal {
pageLength = (self.itemSize.width + self.minimumLineSpacing) * numberOfItemsPerPage
approxPage = collectionView.contentOffset.x / pageLength
speed = velocity.x
} else {
pageLength = (self.itemSize.height + self.minimumLineSpacing) * numberOfItemsPerPage
approxPage = collectionView.contentOffset.y / pageLength
speed = velocity.y
}
if speed < 0 {
currentPage = ceil(approxPage)
} else if speed > 0 {
currentPage = floor(approxPage)
} else {
currentPage = round(approxPage)
}
guard speed != 0 else {
if scrollDirection == .horizontal {
return CGPoint(x: currentPage * pageLength, y: 0)
} else {
return CGPoint(x: 0, y: currentPage * pageLength)
}
}
var nextPage: CGFloat = currentPage + (speed > 0 ? 1 : -1)
let increment = speed / velocityThresholdPerPage
nextPage += (speed < 0) ? ceil(increment) : floor(increment)
if scrollDirection == .horizontal {
return CGPoint(x: nextPage * pageLength, y: 0)
} else {
return CGPoint(x: 0, y: nextPage * pageLength)
}
}
}