Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why UIKit Dynamics doesn`t work?

I am studying iOS development now. When I add a rect view and want it be effected by the gravity, build and run my test app, I find it does`t have the gravity. This is the viewDidLoad code in my viewController.m :

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.
UIView *squre = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
squre.backgroundColor = [UIColor grayColor];
[self.view addSubview:squre];

UIDynamicAnimator *_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
UIGravityBehavior *_gravity = [[UIGravityBehavior alloc] initWithItems:@[squre]];
[_animator addBehavior:_gravity];
like image 936
Morgan Deng Avatar asked Nov 24 '14 01:11

Morgan Deng


1 Answers

Your UIDynamicAnimator is deallocated when viewDidLoad returns. It can't animate anything if it's deallocated. Make a property:

@property (nonatomic) UIDynamicAnimator *animator;

And set it:

self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
like image 183
Aaron Brager Avatar answered Sep 28 '22 06:09

Aaron Brager