Amro's Tumblr RSS

Archive

Dec
13th
Tue
permalink

Springboard Style Wiggles

So you figured out how to setup a UILongPressGestureRecognizer and now you want to make a view “wiggle” back and forth similar to the iOS Springboard app. This is actually pretty simple with Core Animation.
First, setup the view you want to wiggle. The code below assumes it’s called “view.” I’ve found that setting kWiggleAnimationAngle to 0.04 works well.

In your gesture recognizer’s handler:
//Start at negative kWiggleAnimationAngle so we animate to positive kWiggleAnimationAngle
view.layer.transform = CATransform3DMakeRotation(-kWiggleAnimationAngle, 0, 0, 1.0);

//Setup a transform that will rotate our view to positive kWiggleAnimationAngle
CATransform3D transform = CATransform3DMakeRotation(kWiggleAnimationAngle, 0, 0, 1.0);
//Setup our animation with the transform
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@”transform”];
animation.toValue = [NSValue valueWithCATransform3D:transform];
animation.repeatCount = HUGE_VALF;
animation.duration = 0.1;
animation.autoreverses = YES;
[view.layer addAnimation:animation forKey:@”wiggle”];

We’re also setting a few important properties:
- setting repeatCount to HUGE_VALF tells the animation to play indefinitely
- duration is the length of the animation (in one direction)
- autoreverses tells Core Animation to automatically play the animation in reverse once it’s finished
Finally we add the animation to our view’s layer and that’s that. Well, sort of, when we’re ready to stop the animation we need to do the following:

//Remove the animation from our view
[view.layer removeAnimationForKey:@”wiggle”];
//Rotate the view back to its default position
view.layer.transform = CATransform3DMakeRotation(0.0, 0, 0, 1.0);

Resources: Apple’s Core Animation Programming GuideWWDC 2011 VideosAlmost There Stackoverflow Post
Notes: I generally dislike in-app Springboards but sometimes they fit the bill.

Posted via email from amro’s blog | Comment »