Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save coffeeexistence/9c0dd2cfe76d9b6535e3831b5175e33f to your computer and use it in GitHub Desktop.
Save coffeeexistence/9c0dd2cfe76d9b6535e3831b5175e33f to your computer and use it in GitHub Desktop.
[Combine][UIKit][UIScrollView] Horizontal Swipe Direction Detector
import UIKit
import Combine
enum ScrollSwipeDirection {
case leading, trailing, trailingEnd
}
class UIScrollViewHorizontalSwipeEmittingDelegate: NSObject, UIScrollViewDelegate {
public let swipeDirection = PassthroughSubject<ScrollSwipeDirection, Never>()
private var startDraggingOffset: CGFloat = 0
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.startDraggingOffset = scrollView.contentOffset.x
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let contentOffsetDelta = startDraggingOffset - targetContentOffset.pointee.x
if contentOffsetDelta > 0 {
swipeDirection.send(.leading)
} else {
let distanceToEndOffset = scrollView.contentSize.width - scrollView.frame.width - targetContentOffset.pointee.x
swipeDirection.send(distanceToEndOffset <= 0 ? .trailingEnd : .trailing)
}
// Update startDraggingOffset in case Cx swipes in the middle of a momentum scroll
// (which won't trigger scrollViewWillBeginDragging and thus will not set startDraggingOffset)
self.startDraggingOffset = targetContentOffset.pointee.x
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment