本例的运行结果是一个图片可以自由落下,点击鼠标第一次,图片粘附到鼠标点击的位置,点击鼠标第二次,图片自由落下,重复该过程。
需要注意的是,gravity和snap会又些冲突,所以需要以下这一行代码:
dynamicAnimator.removeAllBehaviors()
import UIKit class ViewController: UIViewController { @IBAction func tapped(sender: AnyObject) { let tap = sender as! UITapGestureRecognizer if tap.state == UIGestureRecognizerState.Ended{ let point = tap.locationInView(tap.view) //print(point) self.snap = UISnapBehavior(item: self.dynamicImageView,snapToPoint: point) if (snap != nil){ dynamicAnimator.removeAllBehaviors() dynamicAnimator.addBehavior(self.snap!) if fall==0{ fall=1 }else{ addBehaviorSelf() fall=0 } } } } @IBOutlet weak var dynamicImageView: UIImageView! var fall = 0 var dynamicAnimator = UIDynamicAnimator() var snap: UISnapBehavior? override func viewDidLoad() { super.viewDidLoad() let img1 = UIImage(named:"littleYellowMan.jpg") dynamicImageView.image = img1 dynamicAnimator = UIDynamicAnimator(referenceView: self.view) addBehaviorSelf() } func addBehaviorSelf(){ dynamicAnimator.removeAllBehaviors() let gravityBehavior = UIGravityBehavior(items: [self.dynamicImageView]) dynamicAnimator.addBehavior(gravityBehavior) let collisionBehavior = UICollisionBehavior(items: [self.dynamicImageView]) collisionBehavior.translatesReferenceBoundsIntoBoundary = true dynamicAnimator.addBehavior(collisionBehavior) } }原文链接:https://www.f2er.com/swift/325516.html