UIDynamic物理仿真器
1、首先创建物理仿真器UIDynamicAnimator,并添加仿真范围ReferenceView
//使用懒加载创建仿真器,并使用当前view作为仿真区域 -(UIDynamicAnimator *)animator { if (_animator == nil) { _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; } return _animator; }
2、添加物理行为UIDynamicBehavior
物理行为有:
UIGravityBehavior:重力行为
UICollisionBehavior:碰撞行为
UISnapBehavior:捕捉行为
UIPushBehavior:推动行为
UIAttachmentBehavior:附着行为
UIDynamicItemBehavior:动力元素行为
//添加重力行为 UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[self.view1]]; [self.animator addBehavior:gravity]; //添加碰撞检测行为 UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.view1,self.view2]]; //将当前ReferenceView边界转换为碰撞检测边界 // collision.translatesReferenceBoundsIntoBoundary = YES; //手动画线作为碰撞检测边界 // [collision addBoundaryWithIdentifier:@"line" fromPoint:CGPointMake(0, 200) toPoint:CGPointMake(320, 400)]; //通过贝塞尔曲线绘制碰撞边界 UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 320, 500)]; [collision addBoundaryWithIdentifier:@"circle" forPath:path]; [self.animator addBehavior:collision];
//捕捉行为 -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:touch.view]; UISnapBehavior *snap = [[UISnapBehavior alloc] initWithItem:self.view1 snapToPoint:point]; UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.view1,self.view2]]; collision.translatesReferenceBoundsIntoBoundary = YES; //能够多次调用捕捉行为 [self.animator removeAllBehaviors]; [self.animator addBehavior:collision]; [self.animator addBehavior:snap]; }
浙公网安备 33010602011771号