【发布时间】:2017-08-26 05:03:28
【问题描述】:
我的第一篇文章,我目前正在使用 Swift 3 在 Xcode 8.1 中制作应用程序
我使用 touchesBegan 和 touchesMoved 函数制作了 9 张可拖动的图像。
但是,它们可以在屏幕上的任何位置拖动,这可能会导致它们掩盖我拥有的其他图像。我想通过为他们设置一个边界来限制他们的移动,这样即使用户试图将图像拖出该边界,他们也无法做到。
我在 draggedimageview.swift 中创建了这段代码,它允许拖动图像视图。
我已经花了很长时间试图弄清楚如何做到这一点,如果有人可以提供帮助,我将不胜感激。
谢谢...
import UIKit
class DraggedImageView: UIImageView {
var startLocation: CGPoint?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
startLocation = touches.first?.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let currentLocation = touches.first?.location(in: self)
let dx = currentLocation!.x - startLocation!.x
let dy = currentLocation!.y - startLocation!.y
self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
}
}
【问题讨论】:
-
在设置 self.center 之前,先看看你要设置什么,然后根据你的边界改变它。向我们展示你的尝试。
-
优秀的第一篇文章!继续努力。