在UIView中拖动UILabel并维护它的新坐标

时间:2017-03-30 13:33:05

标签: ios uiview drag-and-drop uipangesturerecognizer

所以我在UILabel nib文件上有UIView,我试图让用户能够拖动标签,当他们停止拖动标签时,如果他们试图他们可以再次拖动它。

我能够使用UIPanGestureRecognizer拖动Label很好,当我停止拖动时,标签会保持原样。我遇到的问题是,当我再次尝试拖动它时,Label会跳回到UIView中心的原始起始位置。

据我所知,当标签开始的实际坐标为UIPanGestureRecognizer.translation(in: UIVIew)时,使用(x: 0.0, y: 0.0)会将原始坐标设为(x: 150.0, y: 90.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的中间位置。

非常感谢任何帮助,因为我在编码方面还很新,谢谢!

2 个答案:

答案 0 :(得分:0)

这可能会有所帮助

CGPoint translation = [recognizer translationInView:self.superview];
testLBL.center = CGPointMake(self.center.x + translation.x, self.center.y + translation.y);
[recognizer setTranslation:CGPointZero inView:self];

快速应用它,你很难找到那么难的

答案 1 :(得分:0)

 // function that helps drag the label around
@objc
func wasDragged(gestureRecognizer: UIPanGestureRecognizer) {

    let translation = gestureRecognizer.translation(in: self.view)
    let selectedLabel = gestureRecognizer.view!

    selectedLabel.center = CGPoint(x: selectedLabel.center.x + translation.x,
                                   y: selectedLabel.center.y + translation.y)
    gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)


    print(["1 x",self.testLbl.frame.origin.x,"y", self.testLbl.frame.origin.y])

}

测试了此代码,它可以工作,希望对任何人都有帮助!