Why UIKit Dynamics doesn`t work?

221 views Asked by At

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];
1

There are 1 answers

0
Aaron Brager On BEST ANSWER

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];