Search code examples
iosswiftuiimageviewuipangesturerecognizerpanning

Why doesn't the UIImageView.center change when panning with UIPanGestureRecognizer (Swift)?


When I use the 'UIPanGestureRecognizer' to move a 'UIImageView' object, I notice the 'center' attribute doesn't change. Why is this, am I doing something wrong? Here is the code:

func handlePanning1(recognizer: UIPanGestureRecognizer)
{
    var index: Int = recognizer.view!.tag - 1 // index in the arrays for this piece

    var newTranslation: CGPoint = recognizer.translationInView(pieces[index])

    recognizer.view?.transform = CGAffineTransformMakeTranslation(lastTranslations[index].x + newTranslation.x, lastTranslations[index].y + newTranslation.y)

    // THIS ALWAYS PRINTS OUT THE SAME WHILE I'M PANNING
    // AND IF I PAN MULTIPLE TIMES IN DIFFERENT DIRECTIONS (AKA IT NEVER CHANGES)
    print(Int(pieces[index].center.x))
    print("\n")

    if recognizer.state == UIGestureRecognizerState.Ended {
        lastTranslations[index].x += newTranslation.x
        lastTranslations[index].y += newTranslation.y
    }
}

Solution

  • You are applying a transform to the view, you are not actually moving it. Think about it as though it is in a certain place but when it gets rendered, there are instructions to skew how it is show. If you want the view to have a different position, then you have to change its center property instead of transforming it.