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];
Your
UIDynamicAnimator
is deallocated whenviewDidLoad
returns. It can't animate anything if it's deallocated. Make a property:And set it: