我正在尝试通过触摸屏幕在屏幕上拖动 UIImageView
。但我希望能够不断移动 Sprite,目前我的代码仅将 Sprite 移动到我触摸的位置,如果我在屏幕上按住触摸一段时间然后移动,Sprite 将随之移动。但是我不想“不得不”触摸 UIImageView
来激活移动,我想触摸屏幕上的任何地方并从 UIImageView
获得移动响应,从它的当前位置。
这是我的代码。
var location = CGPoint()
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
location = touch.locationInView(self.view)
ImageView.center = location}
}
override func prefersStatusBarHidden() -> Bool {
return true
}
感谢您提供的任何帮助。
最佳答案
这是一个更简单的实现。只需记住触摸的最后位置并计算差异,并使用差异来设置图像的新位置。
var lastLocation = CGPoint()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
self.lastLocation = touch.locationInView(self.view)
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let location = touch.locationInView(self.view)
self.imageView.center = CGPoint(x: (location.x - self.lastLocation.x) + self.imageView.center.x, y: (location.y - self.lastLocation.y) + self.imageView.center.y)
lastLocation = touch.locationInView(self.view)
}
}
关于ios - 如何使用 touches 方法拖动 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35008670/