2

I'm trying to create a resizable face with UIPinchGestureRecognizer. All the tutorials online tell me to always reset the scale to 1, such as this code:

func changeScale(byReactingTo pinchRecognizer: UIPinchGestureRecognizer)
{
    switch pinchRecognizer.state {
    case .changed,.ended:
        scale *= pinchRecognizer.scale
        pinchRecognizer.scale = 1
    default:
        break
    } 
}

where scale is a CGFloat that is related to the size of the face.

However, I couldn't find any reasonable explanation as to why pinchRocgnizer.scale always must be reset to 1 after the user pinches. I understand that deleting it could cause erratic behavior, but why?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Luke Yuan
  • 25
  • 5
  • 1
    https://developer.apple.com/reference/uikit/uipinchgesturerecognizer/1622235-scale you can read the documentation. It is not the delta value so you should not concatenate. – Morty Choi May 20 '17 at 13:46
  • @user2215977 But the documentation does not explain why pinchRecognizer.scale has to be reset every time. – Luke Yuan May 21 '17 at 02:45

1 Answers1

3

The documentation have said that the scale of UIPinchGestureRecognizer is calculated from the beginning of gesture recognition. In your code scale *= pinchRecognizer.scale, this is concatenating the value of scale in each invocation during the gesture.

If the value of scale is 1.1, 1.2 then your scale *= pinchRecognizer.scale after the second invocation would be incorrect as its 1.32 not 1.2. So if you change your code to scale = pinchRecognizer.scale you don't need to reset scale of UIPinchGestureRecognizer to zero.

I guess the internal implementation of UIPinchGestureRecognizer is using the scale value to keep track of the relative scale of the UIView to the time the gesture being recognised. So if you reset it to zero, It means the scale is relative to the pervious invocation instead of the first invocation.

Morty Choi
  • 2,466
  • 1
  • 18
  • 26