我试图通过触摸屏幕在屏幕上拖动UIImageView
。但是我希望能够不断移动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
}
感谢您提供的任何帮助。
答案 0 :(得分:2)
这是一个更简单的实现。只需记住触摸的最后位置并计算差异,然后使用差异来设置图像的新位置。
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)
}
}
答案 1 :(得分:0)
以下是我为UIImageView
撰写的代码。代替img,您需要使用sprite
对象。
您需要创建3个全局变量。
var offset: CGPoint
var isHold: Bool
var timerToCheckHold: NSTimer
使用触摸的方法。
func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) {
var touch: UITouch = touches.first!
var location: CGPoint = touch.locationInView(self.view!)
var imgCenter: CGPoint = img.center
offset = CGPointMake(img.center.x - location.x, imgCenter.y - location.y)
timerToCheckHold = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "timerToUpdateHold", userInfo: nil, repeats: false)
}
func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
if timerToCheckHold != nil && timerToCheckHold.isValid() {
timerToCheckHold.invalidate()
}
if isHold {
var touch: UITouch = touches.first!
var location: CGPoint = touch.locationInView(self.view!)
var newcenter: CGPoint = CGPointMake(offset.x + location.x, offset.y + location.y)
img.center = newcenter
}
}
func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent) {
if timerToCheckHold != nil && timerToCheckHold.isValid() {
timerToCheckHold.invalidate()
}
isHold = false
}
您还需要实现计时器方法
func timerToUpdateHold() {
isHold = true
}