Reputation: 10984
I want an image view of some size say 25 by 25, to move in a linear motion from left to right and then right left continuously.
Lets say the image starts moving from left, then at the time it reaches reaches the right, it should start moving back to the left, then this should repeat.
I have this code, which lets the view move down, but I am unable to move it back and forth. This is for UIView.
[UIView beginAnimations:@"MyAnimation" context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:45.0]; // 5 seconds
frame = movingView.frame;
//int j = frame.origin.y;
int i;
for (i= 0; i<=100; i++) {
frame.origin.y += i;//100.0; // Move view down 100 pixels
movingView.frame = frame;
}
How should i do this?
Regards
Upvotes: 1
Views: 1345
Reputation: 24466
It seems you might be making this more complicated than it needs to be. Animate the view center rather than its frame.
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationRepeatAutoreverses:YES];
[UIView setAnimationRepeatCount:HUGE_VAL];
[UIView setAnimationDuration:5.0];
// Animate to right side of the containing view
[movingView setCenter:CGPointMake([[self view] bounds].size.width -
[movingView bounds].size.width / 2.0,
[movingView center].y)];
[UIView commitAnimations];
This will animate the view's center to the right side of the containing view and then automatically return to the start position. Notice I subtract out half of the movingView's width since we're wanting to animate to the right side but we're moving the view's center not its origin.
Setting auto reverse repeat to YES will cause the animation to end up back where it started and then repeat count will cause it to repeat forever.
Also, there is no reason to move the view down one pixel at a time. Just set the ending position you want the view to have and specify an appropriate duration it should take to get there. Core Animation eliminates the need for you to create your own animation loops, timers, or threads.
Upvotes: 3
Reputation: 47034
You don't have to animate things yourself when using UIView animations.
frame = movingView.frame;
frame.origin.x = 0;
movingView.frame = frame; // starting point
[UIView beginAnimations:@"MyAnimation" context:nil];
[UIView setAnimationDuration:5];
frame.origin.x = 320-25;
movingView.frame = frame; // endpoint
[UIView commitAnimations];
for a move from left to right. To wait for the end, use setAnimationDidStopSelector
to call a method which does the opposite animation.
Have a look at flipping uiview continuously for the animation delegate stuff.
Upvotes: 1