how to do a continuous recycling UIView animation

2019-03-29 05:47发布

问题:

The following code move the the imageview from right to left once, but I want to do continously. move right to to left then move back to left offscreen and repeat right to left again.

imageview=[[UIImageView alloc] initWithFrame:CGRectMake(320, 200, 2635, 200)];

image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"animal" ofType:@"png"]]; 
               [imageview setImage:image];

[self.view addSubview:imageview];

[UIView beginAnimations:@"MoveAndStrech" context:nil];
[UIView setAnimationDuration:40];     //30
[UIView setAnimationBeginsFromCurrentState:YES];
CGPoint p, b, a, c, d,e;
p.x = 0;
p.y = 200;

imageview.center=p;

[UIView commitAnimations];  

回答1:

Add the following lines:

[UIView setAnimationRepeatCount: HUGE_VAL];
[UIView setAnimationRepeatAutoreverses: YES];

Or if you target iOS 4.0+ then blocked-based animations are preferred:

[UIView animateWithDuration:40.0f
                      delay:0.0f
                    options: UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionBeginFromCurrentState
                 animations: ^(void){imageview.center = CGPointMake(0, 200);}
                 completion:NULL];