[Objc] UIDynamicAnimator with CMMotionManager

Today a funny article that use both UIDynamicAnimator and CMMotionManager!


We want to drop down all of the UI object on the screen and move around using phone motion.

How to?

First of all import in your project CoreMotion framework,

#import <CoreMotion/CoreMotion.h>;

Next, add as STRONG properties two vars,

@property (nonatomic, strong) UIDynamicAnimator *animator;
@property (nonatomic, strong) CMMotionManager   *motionManager;

Connect all of your IBOutlets on screen and add to an array:

dynamics and motion

NSArray *items = @[_lbl1, _lbl2, _lbl3, _lbl4, _lbl5, _lbl6, 
                   _view1, _view2,
	           _button, _switch, _seg, _txt, _spin];

where you want, start coding:

Instantiate the animator:
self.animator = [[UIDynamicAnimator alloc] 
Instantiate the gravity behavior:
UIGravityBehavior* gravityBehavior = [[UIGravityBehavior alloc] 
[self.animator addBehavior:gravityBehavior];
Instantiate and configurate the collision behavior:
UICollisionBehavior* collisionBehavior = 
   [[UICollisionBehavior alloc] initWithItems:items];
collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:collisionBehavior];
Instantiate the item behavior and configure the elasticity (for bounce):
UIDynamicItemBehavior *elasticityBehavior = 
     [[UIDynamicItemBehavior alloc] initWithItems:items];
elasticityBehavior.elasticity = 0.5f;
[self.animator addBehavior:elasticityBehavior];
Next and for last, start the motion manager:
self.motionManager = [[CMMotionManager alloc] init];
[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]  withHandler:^(CMDeviceMotion *motion, NSError *error) {
	CMAcceleration gravity = motion.gravity;
	dispatch_async(dispatch_get_main_queue(), ^{
		gravityBehavior.gravityDirection = CGVectorMake(gravity.x, -gravity.y);

and obviously stop when you finish use it

[self.motionManager stopDeviceMotionUpdates];


Final result here:


Want “full code”? .m file is on github gist.



Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.