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.
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.
I've found that this is the simplest and most flexible option (it works for UICollectionView and UITableView as well).
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.
For swift4
Simply add this method to your view controller:
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:
And there you go. Again, if you need to track constantly, use Victors answer, otherwise I prefer this solution.
If you use an
UIScrollView
then you can take benefit from thescrollViewDidScroll:
function. You need to save the last position (thecontentOffset
) it have and the update it like in the following way:There are other ways of do it of course this is one to them.
I hope this help you.
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:
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:
3) In the scrollViewDidScroll add the following:
4) If you have not implemented scrollViewDidEndDragging implement it and add these lines of code inside it:
5) If you have not implemented scrollViewWillBeginDecelerating implement it and add this line of code inside it:
6) Finally, If you have not implemented scrollViewWillBeginDragging implement it and add this line of code inside it:
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: