如何使用touches方法拖动UIImageView [英] How to drag UIImageView using touches method

查看:22
本文介绍了如何使用touches方法拖动UIImageView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过触摸屏幕在屏幕周围拖动 UIImageView.但是我希望能够不断移动精灵,目前我的代码只将精灵移动到我触摸的位置,如果我在屏幕上按住触摸一段时间然后移动,精灵将跟随.但是我不想必须"触摸 UIImageView 来激活运动,我想触摸屏幕上的任何地方并从 UIImageView 获得运动响应,从其当前位置.

I'm trying to drag a UIImageView around the screen by touching the screen. But I want to be able to do a constant movement of the Sprite, currently my code only moves the sprite to the location of my touch and if I hold on touch on screen for some amount of time and then move, the sprite will follow. However I don't want to "have" to touch the UIImageView to activate the movement, I want to touch anywhere on the screen and have a movement response from that UIImageView, from its current location.

这是我的代码.

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
}

感谢您提供的任何帮助.

Thank you for any help you may provide.

推荐答案

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

Here is a simpler implementation. Just remember the last location of the touch and compute the difference, and use the difference to set the new location of the image.

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)
    }
}

这篇关于如何使用touches方法拖动UIImageView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆