2

I have a calendar based app

app

I want the user to be able to pinch to zoom in and out of the calendar. This is my code:

let p = UIPinchGestureRecognizer(target: self, action: #selector(pinch))
view.addGestureRecognizer(p)

@objc func pinch(gestureRecognizer gesture: UIPinchGestureRecognizer) {
    print("----------")
    print("Spacing: \(timeStack.spacing)")
    print("Gesture: \(gesture.scale)")
    var spacing = timeStack.spacing * gesture.scale
    if spacing > 70 {
        spacing = 70
    } else if spacing < 10 {
        spacing = 10
    }
    timeStack.spacing = spacing
}

I have a UIStackView that contains the labels called timeStack, and my code is changing its spacing according to the scale from the gesture.

This is what happens when I run it. It does work but even the most small gesture resize it and it's very unnatural:

gif

I was wondering how I can improve my code so it's more like the pinch to zoom in the iOS calendar app. Thank you.

אורי orihpt
  • 2,358
  • 2
  • 16
  • 41
  • You must keep the spacing at the beginning of the gesture as the scale is valid for this value only. New spacing is spacing at beginning of gesture x new scale – Ptit Xav Apr 14 '21 at 11:54
  • 2
    Add : gesture.scale = 1.0 after setting new value of time stack.spacing – Ptit Xav Apr 14 '21 at 12:01

1 Answers1

5

Reset scale each time :

@objc func pinch(gestureRecognizer gesture: UIPinchGestureRecognizer) {
    print("----------")
    print("Spacing: \(timeStack.spacing)")
    print("Gesture: \(gesture.scale)")
    var spacing = timeStack.spacing * gesture.scale
    if spacing > 70 {
        spacing = 70
    } else if spacing < 10 {
        spacing = 10
    }
    timeStack.spacing = spacing
    // reset gesture scale to prevent cumulative effect
    gesture.scale = 1.0
}
Ptit Xav
  • 3,006
  • 2
  • 6
  • 15