Search code examples
iphoneiosobjective-cuiscrollviewuiscrollviewdelegate

check if scrollview.contentset went over certain x value


I have a scrollview and above some image. When the scrollview scrollView.contentOffset.x is past a certain X my image above should animate.

I know how to animate. At the moment I'm doing this in the - (void)scrollViewDidScroll:(UIScrollView *)scrollView method.

if (scrollView.contentOffset.x == 160) {
 //animate Image
}

but sometimes it gets the 160, but other times it passes over the 160. How can I solve this ?


Solution

  • Add an instance variable, set it to the offset that you've seen in the last invocation of scrollViewDidScroll:, and use it to decide if you would like to animate:

    // Instance variable
    CGPoint lastOffset;
    ...
    - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
        ...
        if (lastOffset.x < 160 && scrollView.contentOffset.x >= 160) {
            //animate Image
        }
        lastOffset = scrollView.contentOffset;
    }
    

    This would let you animate the image every time the scroll view crosses from below 160 to above 160.