0

In my application I use UILongPressGestureRecognizer to drag a view around the screen. This view has some subviews, including an UILabel, which are laid out using constraints. When I begin dragging, I make sure to remove all positioning constraint from the dragged view (I keep the width & height constraints), as I update frame manually as the gesture recogniser changes. This works well, but when I update the text of a subview label while dragging, the view being dragged jumps to (0,0) for a split second, but returns to the correct location after I drag some more which calls another update to frame.

When the gesture recogniser is called with a .changed state, the following code is ran:

let location = gesture.location(in: calendar.view)
moveView(with: location)

This works perfectly fine, the view follows the finger and doesn't jump around.

Now I want to add a label that is updated as the location changes:

let location = gesture.location(in: calendar.view)
moveView(with: location)

movingView.label.text = "Some Text: \(location.x ?? "Error")"

Now the view jumps to (0,0) all the time.

I have tried to get around this issue by taking the old frame and then setting it after I update the text like this:

let location = gesture.location(in: calendar.view)
moveView(with: location)

let oldFrame = movingView.frame
movingView.label.text = "Some Text: \(location.x ?? "Error")"
//movingView.layoutIfNeeded() -> tried with this too, to no effect
movingView.frame = oldFrame

Still, however, the view jumps to (0,0). So my question is, what can be done about this? How can I set the text of an UILabel without messing up the dragging of the view?

Denis Balko
  • 1,566
  • 2
  • 15
  • 30

1 Answers1

2

Keep the view with all the constraints as they are, and use transform to move the view around when gestureRecognizer.location changes:

label.transform = CGAffineTransform.identity.translatedBy(x: location.x, y: location.y)
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90