我试图通过触摸屏幕来拖动屏幕上的UIImageView。但是我希望能够不断地移动雪碧,目前我的代码只将精灵移动到我触摸的位置,如果我在屏幕上停留了一段时间,然后移动,精灵就会跟着移动。但是,我不想“不得不”触摸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
}感谢您提供的任何帮助。
发布于 2016-01-26 08:31:37
这里有一个更简单的实现。只需记住触摸的最后位置并计算差异,并使用差异设置图像的新位置。
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)
}
}发布于 2016-01-26 08:26:02
下面是我为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
}此外,您还需要实现timer方法。
func timerToUpdateHold() {
isHold = true
}https://stackoverflow.com/questions/35008670
复制相似问题