How to get UIScrollView vertical direction in Swift?

前端 未结 12 993
悲&欢浪女
悲&欢浪女 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:45

    I've found that this is the simplest and most flexible option (it works for UICollectionView and UITableView as well).

    override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
    
        switch velocity {
        case _ where velocity.y < 0:
            // swipes from top to bottom of screen -> down
            trackingDirection = .down
        case _ where velocity.y > 0:
            // swipes from bottom to top of screen -> up
            trackingDirection = .up
        default: trackingDirection = .none
        }
    }
    

    Where this doesn't work though, is if there is 0 velocity - in which case you'll have no choice but to use the accepted answer's stored property solution.

提交回复
热议问题