Created
May 19, 2021 06:29
-
-
Save coffeeexistence/9c0dd2cfe76d9b6535e3831b5175e33f to your computer and use it in GitHub Desktop.
[Combine][UIKit][UIScrollView] Horizontal Swipe Direction Detector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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