【发布时间】:2017-03-30 13:33:05
【问题描述】:
所以我在UIView nib 文件上有一个UILabel,我试图让用户能够拖动标签,当他们停止拖动标签时,标签会停留在那里,如果他们再次尝试拖动它,他们可以。
我可以使用UIPanGestureRecognizer 很好地拖动标签,当我停止拖动它时,标签会保持在原来的位置。我遇到的问题是,当我尝试再次拖动它时,标签会跳回到UIView 中心的原始起始位置。
我知道,当标签开始的实际坐标是(x: 150.0, y: 90.0) 时,使用UIPanGestureRecognizer.translation(in: UIVIew) 会给出原始坐标为(x: 0.0, y: 0.0)。
@IBOutlet var cardView: UIView!
@IBOutlet weak var testLBL: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// trying to move the label
let gesture = UIPanGestureRecognizer(target: self, action: #selector(self.wasDragged(gestureRecognizer:)))
testLBL.isUserInteractionEnabled = true
cardView.clipsToBounds = true
testLBL.addGestureRecognizer(gesture)
}
下面是用于处理动作的函数,我尝试过的其他几件事都被注释掉了。我还在cardView 中打印标签的当前坐标
// function that helps drag the label around
func wasDragged(gestureRecognizer: UIPanGestureRecognizer) {
let translation = gestureRecognizer.translation(in: cardView)
//print(translation)
// currently taking it from the original point each time you try to drag it
testLBL.center = CGPoint(x: self.bounds.width / 2 + translation.x, y: self.bounds.height / 2 + translation.y)
//how you will know what position the label was moved to
print(["x",self.testLBL.frame.origin.x,"y", self.testLBL.frame.origin.y])
//let newTranslation = gestureRecognizer.translation(in: cardView)
//var coordinates = CGPoint(x: self.testLBL.frame.origin.x, y: self.testLBL.frame.origin.y)
}
testLBL.center = CGPoint(x: self.bounds.width / 2 + translation.x, y: self.bounds.height / 2 + translation.y) 操作是允许标签移动和工作的原因,我只是希望它在我再次尝试拖动它时不要跳回UIView 的中间。
非常感谢任何帮助,因为我在编码方面还是新手,谢谢!
【问题讨论】:
-
你可以使用触摸事件方法...
-
我对使用它们不是很熟悉,能否看到我应该如何使用它的示例?
-
@JimmyPayne 检查我自己的答案stackoverflow.com/questions/37747693/draggable-label-ios/… 我希望这对你有帮助
标签: ios uiview drag-and-drop uipangesturerecognizer