How to get UIScrollView vertical direction in Swift?

前端 未结 12 1010
悲&欢浪女
悲&欢浪女 2020-12-01 01:51

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

12条回答
  •  无人及你
    2020-12-01 02:43

    Victor's answer is great, but it's quite expensive, as you're always comparing and storing values. If your goal is to identify the scrolling direction instantly without expensive calculation, then try this using Swift:

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        let translation = scrollView.panGestureRecognizer.translation(in: scrollView.superview)
        if translation.y > 0 {
            // swipes from top to bottom of screen -> down
        } else {
            // swipes from bottom to top of screen -> up
        }
    }
    

    And there you go. Again, if you need to track constantly, use Victors answer, otherwise I prefer this solution.

提交回复
热议问题