Skip to content

Instantly share code, notes, and snippets.

@frijole
Created September 13, 2013 15:02
Show Gist options
  • Save frijole/6551892 to your computer and use it in GitHub Desktop.
Save frijole/6551892 to your computer and use it in GitHub Desktop.
track a UIScrollView's direction, based on http://stackoverflow.com/a/16953031
typedef NS_ENUM(NSInteger, UIScrollViewScrollDirection) {
UIScrollViewScrollDirectionDown = -1,
UIScrollViewScrollDirectionNone = 0,
UIScrollViewScrollDirectionUp = 1,
};
@interface FRJViewController ()
@property (nonatomic) UIScrollViewScrollDirection scrollDirection;
@end
@implementation FRJViewController
- (id)init
{
if ( self = [super init] )
{
UIScrollView *scrollView = [UIScrollView alloc] initWithFrame:CGRectZero];
// configuration
[self.view addSubview:scrollView];
[scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
CGFloat newContentOffset = [[change objectForKey:@"new"] CGPointValue].y;
CGFloat oldContentOffset = [[change objectForKey:@"old"] CGPointValue].y;
CGFloat diff = newContentOffset - oldContentOffset;
if ( diff < 0 )
{
//scrolling down
self.scrollDirection = UIScrollViewScrollDirectionDown;
}
else if ( diff > 0 )
{
// scrolling up
self.scrollDirection = UIScrollViewScrollDirectionUp;
}
else
{
// not scrolling
self.scrollDirection = UIScrollViewScrollDirectionNone;
}
}
// ...
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment