Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get UIScrollView vertical direction in Swift?

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 down and then hide/show a UIView depending if it was an up/down gesture.

like image 762
user2722667 Avatar asked Aug 06 '15 13:08

user2722667


2 Answers

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 } 

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

I hope this help you.

like image 64
Victor Sigler Avatar answered Sep 23 '22 01:09

Victor Sigler


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. 😊

like image 22
GLS Avatar answered Sep 21 '22 01:09

GLS