[Objc] UIDynamicAnimator with CMMotionManager

Today a 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  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:
* collisionBehavior = 
   [[ alloc] initWithItems:items];
collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:collisionBehavior];
Instantiate the item behavior and configure the (for bounce):
 *elasticityBehavior = 
     [[ 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 :[NSOperationQueue mainQueue]  withHandler:^(CMDeviceMotion *motion, NSError *error) {
	CMAcceleration gravity = motion.gravity;
	dispatch_async(dispatch_get_main_queue(), ^{
		gravityBehavior. = (gravity.x, -gravity.y);

and obviously stop when you finish use it

[self.motionManager stopDeviceMotionUpdates];


Final result here:


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