Question

I'm attempting to run an animation so that the scrollview's contentoffset gets continually scrolling down.

However, after each repeat, it will animate from the original position and it is not progressing.

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration:1.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationRepeatCount: 100];

CGPoint contentOffset = scrollView.contentOffset;
contentOffset.y += 50;
scrollView.contentOffset = contentOffset;

scrollView.transform = CGAffineTransformIdentity;  
[UIView commitAnimations];

any ideas ?

Was it helpful?

Solution

Why are you attempting to manually scroll the view? Can't you use the method

- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated

?

Regardless, I believe the reason your animation isn't working as you expect is because you're setting a repeat count instead of actually re-rendering your animation each time. If you want to work around this problem, you could animate again in the animation callback by creating a method wrapping the animation and passing parameters via the context pointer.

- (void) animateContentOffsetByAmount:(CGFloat)amount numberRemaining:(int)num {
    if (num == 0) return;

    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:
        @selector(scrollAnimationStoppedWithID:finished:context:)];

    //NSArray released in callback
    NSArray* contextArray = [NSArray arrayWithObjects:
      [NSNumber numberWithFloat:amount],
      [NSNumber numberwithInt:num], nil]
    [UIView beginAnimations:nil context:contextArray];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

    CGPoint contentOffset = scrollView.contentOffset;
    contentOffset.y += amount;
    scrollView.contentOffset = contentOffset;

    scrollView.transform = CGAffineTransformIdentity;  
    [UIView commitAnimations];
}

- (void) scrollAnimationStoppedWithID:(NSString*)id
        finished:(NSNumber*)finished context:(void*)context {
    NSArray* contextArray = (NSArray*)context;
    CGFloat amount = [(NSNumber*)[contextArray objectAtIndex:0] floatValue];
    int count = [(NSNumber*)[contextArray objectAtIndex:1] intValue];
    count = count - 1;
    [contextArray release];
    [self animateContentOffsetByAmount:amount numberRemaining:count]
}

Then in your code, just call

[self animateContentOffsetByAmount:50 numberRemaining:100];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top