How to get UIScrollView vertical direction in Swift?

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

    I made protocol to reuse Scroll Directions.

    Declare these enum and protocols.

    enum ScrollDirection {
        case up, left, down, right, none
    }
    
    protocol ScrollDirectionDetectable {
        associatedtype ScrollViewType: UIScrollView
        var scrollView: ScrollViewType { get }
        var scrollDirection: ScrollDirection { get set }
        var lastContentOffset: CGPoint { get set }
    }
    
    extension ScrollDirectionDetectable {
        var scrollView: ScrollViewType {
            return self.scrollView
        }
    }
    

    Usage From ViewController

    // Set ScrollDirectionDetectable which has UIScrollViewDelegate
    class YourViewController: UIViewController, ScrollDirectionDetectable {
        // any types that inherit UIScrollView can be ScrollViewType
        typealias ScrollViewType = UIScrollView
        var lastContentOffset: CGPoint = .zero
        var scrollDirection: ScrollDirection = .none
    
    }
        extension YourViewController {
            func scrollViewDidScroll(_ scrollView: UIScrollView) {
                // Update ScrollView direction
                if self.lastContentOffset.x > scrollView.contentOffset.x {
                    scrollDirection = .left
                } else if self.lastContentOffset.x > scrollView.contentOffset.x {
                    scrollDirection = .right
                }
    
                if self.lastContentOffset.y > scrollView.contentOffset.y {
                    scrollDirection = .up
                } else if self.lastContentOffset.y < scrollView.contentOffset.y {
                    scrollDirection = .down
                }
                self.lastContentOffset.x = scrollView.contentOffset.x
                self.lastContentOffset.y = scrollView.contentOffset.y
            }
        }
    

    If you want to use specific direction, just update specific contentOffset that you want.

提交回复
热议问题