首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用touches方法拖动UIImageView

如何使用touches方法拖动UIImageView
EN

Stack Overflow用户
提问于 2016-01-26 07:19:38
回答 2查看 1.2K关注 0票数 3

我试图通过触摸屏幕来拖动屏幕上的UIImageView。但是我希望能够不断地移动雪碧,目前我的代码只将精灵移动到我触摸的位置,如果我在屏幕上停留了一段时间,然后移动,精灵就会跟着移动。但是,我不想“不得不”触摸UIImageView来激活移动,我想要触摸屏幕上的任何位置,并从该UIImageView中从其当前位置得到一个移动响应。

这是我的密码。

代码语言:javascript
复制
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
}

感谢您提供的任何帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-26 08:31:37

这里有一个更简单的实现。只需记住触摸的最后位置并计算差异,并使用差异设置图像的新位置。

代码语言:javascript
复制
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)
    }
}
票数 4
EN

Stack Overflow用户

发布于 2016-01-26 08:26:02

下面是我为UIImageView编写的代码。代替img,您需要使用您的sprite对象。

您需要创建3个全局变量。

代码语言:javascript
复制
var offset: CGPoint
var isHold: Bool
var timerToCheckHold: NSTimer

使用触摸的方法。

代码语言:javascript
复制
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方法。

代码语言:javascript
复制
func timerToUpdateHold() {
    isHold = true
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35008670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档