我正在尝试使用Xcode编写代码来拖动图像,以便可以四处移动图像,当我放下图像时,可能会产生重力效果。我为图像创建了一个名为DraggedImageView的新类(继承自UIImageView),并进行了以下更改:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
startLocation = touches.first?.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let currentLocation = touches.first?.location(in: self)
let dx = currentLocation!.x - startLocation!.x
let dy = currentLocation!.y - startLocation!.y
self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
}
在我的ViewController中,我有:
import UIKit
class ViewController: UIViewController {
// Moving background items
@IBOutlet weak var groundView: UIImageView!
@IBOutlet weak var background1View: UIImageView!
@IBOutlet weak var background2View: UIImageView!
@IBOutlet weak var background3View: UIImageView!
@IBOutlet weak var cloud1View: UIImageView!
@IBOutlet weak var cloud2View: UIImageView!
// Main character items
@IBOutlet weak var marioView: DraggedImageView!
// Behavior items
var dynamicAnimator: UIDynamicAnimator!
var collisionBehavior: UICollisionBehavior!
var gravityBehavior: UIGravityBehavior!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(background1View)
self.view.addSubview(background2View)
self.view.addSubview(background3View)
self.view.addSubview(groundView)
self.view.addSubview(cloud1View)
self.view.addSubview(cloud2View)
self.view.addSubview(marioView)
dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
gravityBehavior = UIGravityBehavior(items: [marioView])
dynamicAnimator.addBehavior(gravityBehavior)
gravityBehavior.magnitude = 0.5
collisionBehavior = UICollisionBehavior(items: [marioView])
collisionBehavior.translatesReferenceBoundsIntoBoundary = true
dynamicAnimator.addBehavior(collisionBehavior)
}
问题在于主角只掉落一次,当我尝试再次将其拖上时,gravityBehaviour无法正常工作。同样,根据我执行代码的模拟器,冲突的边界也不正确。
我只是希望它具有正确的行为,但是我已经尝试了很多方法,但我做不到。