How to get UIScrollView vertical direction in Swift?

If you use an UIScrollView then you can take benefit from the scrollViewDidScroll: function. You need to save the last position (the contentOffset) it have and the update it like in the following way:

// variable to save the last position visited, default to zero
 private var lastContentOffset: CGFloat = 0

 func scrollViewDidScroll(_ scrollView: UIScrollView) {
     if (self.lastContentOffset > scrollView.contentOffset.y) {
         // move up
     }
     else if (self.lastContentOffset < scrollView.contentOffset.y) {
        // move down
     }

     // update the new position acquired
     self.lastContentOffset = scrollView.contentOffset.y
     print(lastContentOffset)
 }

There are other ways of doing it of course this is one of them.

I hope this helps you.

Leave a Comment