ios - 如何使用 touches 方法拖动 UIImageView

标签 ios swift uiimage

我正在尝试通过触摸屏幕在屏幕上拖动 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/

相关文章:

ios - 尝试让 Apple Watch 计时器应用程序在屏幕关闭时在后台运行

javascript - Nativescript Google map - 更改折线颜色

ios - Swift UITableViewCell 显示默认隐藏的数据

ios - 行分隔符上的标签 - Swift Tableview - 每小时日历

swift : how to show error message in webview when there is no internet connection?

iphone - MFMailComposeViewController : Attaching Images from Photo Gallery

ios - prepareForSegue 什么时候被调用?

swift - 如何通过动画 UIView 将 UIImage 设置到 SWIFT 中的另一个 View Controller

ios - Swift UIButton 覆盖,setImage 不工作

ios - 从 XML 提要中抓取图像的更快方法