Now that I’ve popped my App Store cherry, I’m ready to get serious. I’ve started working on a project that requires the animation of a UIView. For this post I’ve created the following scene where the red box moves to a random point within the white box whenever the user clicks the “Move Red Box” button:

Download the project here to look at how everything works. The magic happens in the TopView.m file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
-(void)moveBoxTo:(CGPoint)point {
CGRect frame = self.box.frame; //where self.box is the Red Box
frame.origin.x = point.x; // new x coordinate (int)
frame.origin.y = point.y; // new y coordinate (int)
[UIView animateWithDuration:1.0
delay: 0.0
options: UIViewAnimationOptionCurveEaseInOut
animations:^{
self.box.frame = frame; //This is what will animate
}
completion:^(BOOL finished){
//do something on finish
}];
} |
Whenever moveBoxTo is triggered, the x and y coordinates defined in the point parameter are used to reposition it. The parameters are:
- animateWithDuration
As the name suggests, the duration for the animation.
- delay
You can delay the start of the animation (in seconds) here.
- options
Here you can define the type of animation, such as easing in or out. See UIView Class Reference for the options available.
- animations
A block which defines what properties the target object should animate. In this case, I’m animating the frame property.
- Completion
Another block which is triggered once the animation completes.
Here’s an example of how you might call the method:
|
|
int x = random() % 300; // random number, max of 300
int y = random() % 400; // random number, max of 400
CGPoint point = CGPointMake(x,y); //create the CGPoint to pass along
[self.box moveBoxTo:point]; // trigger moveBoxTo method |
Download Project File
I’ve skipped over the finer points to keep things simple. Download the project file here to poke around :)