4

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 ?

Steaphann
  • 2,797
  • 6
  • 50
  • 109

3 Answers3

3

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Use >= 160 but also use a flag so you know if you have already done the animation:

if (scrollView.contentOffset.x == 160 && !self.animatedImage) {
    self.animatedImage = YES;
    ...
}
Wain
  • 118,658
  • 15
  • 128
  • 151
0

I think you should add some flag to allow image animation, and manage this flag during scrolling/after image animating

BOOL isCanAnimate_;
// some code here


- (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{
       if (scrollView.contentOffset.x >= imageView.frame.size.width / 2 && isCanAnimate_) 
       {

        isCanAnimate_ = FALSE;

        [UIView animateWithDuration:2.0 
                              delay:0.0 
                            options:UIViewAnimationOptionAllowUserInteraction
                         animations:^
         {
             // Animation here
         } 
         completion:^(BOOL finished) 
         {
              isCanAnimate_ = TRUE;
         }];
     }
}