//创建物理仿真器
UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
self.animator = animator; //强引用animator,否则代码块执行完成后,将被释放
//创建重力行为
UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[self.view1]];
//设置一些属性(可以不设置,不设则都为默认)
gravityBehavior.gravityDirection = CGVectorMake(0, 1); //重力方向
gravityBehavior.angle = M_PI*0.5; //重力方向
gravityBehavior.magnitude = 0.5; //重力加速度,1代表加速度是(每秒100个点)
//把重力行为行为添加到仿真器
[animator addBehavior:gravityBehavior];
//创建碰撞行为
UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[self.view1,self.view2]];
//设置碰撞边界,不设置就会飞出屏幕,设置就会在屏幕边框处产生碰撞效果
collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
//将碰撞行为加入物理仿真器
[animator addBehavior:collisionBehavior];
二,捕捉行为
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //获取触摸点 UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:touch.view]; //创建仿真仿真器 UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; self.animator = animator; //仿真器 //创建捕捉行为 UISnapBehavior *snapBehavior = [[UISnapBehavior alloc] initWithItem:self.redView snapToPoint:point]; //设置反弹系数(反弹幅度越大,值越大,反弹幅度越小) snapBehavior.damping = 0.5; //将行为添加到仿真器 [animator addBehavior:snapBehavior]; }
原文:http://www.cnblogs.com/tongyuling/p/4611116.html