Search code examples
iphonescrolluiscrollview

iPhone UIScrollView Speed Check


I know how to get the contentOffset on movement for a UIScrollView, can someone explain to me how I can get an actual number that represents the current speed of a UIScrollView while it is tracking, or decelerating?


Solution

  • Have these properties on your UIScrollViewDelegate

    CGPoint lastOffset;
    NSTimeInterval lastOffsetCapture;
    BOOL isScrollingFast;
    

    Then have this code for your scrollViewDidScroll:

    - (void) scrollViewDidScroll:(UIScrollView *)scrollView {    
        CGPoint currentOffset = scrollView.contentOffset;
        NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
    
        NSTimeInterval timeDiff = currentTime - lastOffsetCapture;
        if(timeDiff > 0.1) {
            CGFloat distance = currentOffset.y - lastOffset.y;
            //The multiply by 10, / 1000 isn't really necessary.......
            CGFloat scrollSpeedNotAbs = (distance * 10) / 1000; //in pixels per millisecond
    
            CGFloat scrollSpeed = fabsf(scrollSpeedNotAbs);
            if (scrollSpeed > 0.5) {
                isScrollingFast = YES;
                NSLog(@"Fast");
            } else {
                isScrollingFast = NO;
                NSLog(@"Slow");
            }        
    
            lastOffset = currentOffset;
            lastOffsetCapture = currentTime;
        }
    }
    

    And from this i'm getting pixels per millisecond, which if is greater than 0.5, i've logged as fast, and anything below is logged as slow.

    I use this for loading some cells on a table view animated. It doesn't scroll so well if I load them when the user is scrolling fast.