Today a funny article that use both UIDynamicAnimator and CMMotionManager!
What?
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:
NSArray *items = @[_lbl1, _lbl2, _lbl3, _lbl4, _lbl5, _lbl6, _view1, _view2, _button, _switch, _seg, _txt, _spin];
Well,
where you want, start coding:
Instantiate the animator:
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
Instantiate the gravity behavior:
UIGravityBehavior* gravityBehavior = [[UIGravityBehavior alloc] initWithItems:items]; [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];
Oooook!
Final result here:
Want “full code”? .m file is on github gist.
enjoy!