How can I get the scroll/swipe direction for up/down in a VC?
I want to add a UIScrollView or something else in my VC that can see if the user swipes/scrolls up or d
I have tried every single response in this thread but none of them could provide a proper solution for a tableView with bounce enabled. So I just used parts of solutions along with some all-time classic boolean flag solution.
1) So, first of all you could use an enum for the scrollDirection:
enum ScrollDirection {
case up, down
}
2) Set 3 new private vars to help us store lastOffset, scrollDirection and a flag to enable/disable the scroll direction calculation (helps us ignore the bounce effect of tableView) which you will use later:
private var shouldCalculateScrollDirection = false
private var lastContentOffset: CGFloat = 0
private var scrollDirection: ScrollDirection = .up
3) In the scrollViewDidScroll add the following:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// The current offset
let offset = scrollView.contentOffset.y
// Determine the scolling direction
if lastContentOffset > offset && shouldCalculateScrollDirection {
scrollDirection = .down
}
else if lastContentOffset < offset && shouldCalculateScrollDirection {
scrollDirection = .up
}
// This needs to be in the last line
lastContentOffset = offset
}
4) If you have not implemented scrollViewDidEndDragging implement it and add these lines of code inside it:
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard !decelerate else { return }
shouldCalculateScrollDirection = false
}
5) If you have not implemented scrollViewWillBeginDecelerating implement it and add this line of code inside it:
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
shouldCalculateScrollDirection = false
}
6) Finally, If you have not implemented scrollViewWillBeginDragging implement it and add this line of code inside it:
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
shouldCalculateScrollDirection = true
}
And if you followed all the steps above you are good to go!
You could go to wherever you want to use the direction and simply write:
switch scrollDirection {
case .up:
// Do something for scollDirection up
case .down:
// Do something for scollDirection down
}