【问题标题】:Dragging a UILabel within a UIView and maintaining it's new coordinates在 UIView 中拖动 UILabel 并保持其新坐标
【发布时间】: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 的中间。

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

【问题讨论】:

标签: ios uiview drag-and-drop uipangesturerecognizer


【解决方案1】:
 // 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])

}

测试了这段代码,它可以工作,希望它可以帮助任何人!

【讨论】:

    【解决方案2】:

    这可能会有所帮助

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

    快速应用它,你不会觉得那么难

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 2011-04-20
      相关资源
      最近更新 更多