Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UIDynamics and CCMotionManager
//
// ViewController.m
// DynamicMotion
//
// Created by Alberto Pasca on 20/05/15.
// Copyright (c) 2015 Alberto Pasca. All rights reserved.
//
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
{
IBOutlet UILabel *_lbl1;
IBOutlet UILabel *_lbl2;
IBOutlet UILabel *_lbl3;
IBOutlet UILabel *_lbl4;
IBOutlet UILabel *_lbl5;
IBOutlet UILabel *_lbl6;
IBOutlet UIView *_view1;
IBOutlet UIView *_view2;
IBOutlet UIButton *_button;
IBOutlet UISwitch *_switch;
IBOutlet UISegmentedControl *_seg;
IBOutlet UITextField *_txt;
IBOutlet UIActivityIndicatorView *_spin;
}
@property (nonatomic, strong) UIDynamicAnimator *animator;
@property (nonatomic, strong) CMMotionManager *motionManager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *items = @[_lbl1, _lbl2, _lbl3, _lbl4, _lbl5, _lbl6, _view1, _view2,
_button, _switch, _seg, _txt, _spin];
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
UIGravityBehavior* gravityBehavior = [[UIGravityBehavior alloc] initWithItems:items];
[self.animator addBehavior:gravityBehavior];
UICollisionBehavior* collisionBehavior = [[UICollisionBehavior alloc] initWithItems:items];
collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:collisionBehavior];
UIDynamicItemBehavior *elasticityBehavior = [[UIDynamicItemBehavior alloc] initWithItems:items];
elasticityBehavior.elasticity = 0.5f;
[self.animator addBehavior:elasticityBehavior];
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);
});
}];
}
@end
@Henry4Zhang

This comment has been minimized.

Copy link

@Henry4Zhang Henry4Zhang commented Oct 23, 2015

Hi Pasca,

Now I had a requirement of let some tag rotate from an anchor point with the gravity, can you tell me which property should I set to the UIDynamicItemBehavior?

Thanks very much
Henry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment