How to get UIScrollView vertical direction in Swift?

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

    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
    }
    

提交回复
热议问题