0
votes

I'm trying to use a Pinch Gesture Recognizer to scale a UITextView up and down, however it always starts at a scale of 1.0. I've tried to implement these answers:
iOS Pinch Zoom Start from Previous Scale
UIPinchGestureRecognizer. Make zoom in location of fingers, not only center
Pinch gesture scale resetting to 1?

but i must be doing something wrong, because it still resets to a scale of 1.0 each time. Here's my code:

@objc func pinchRecognized(recognizer: UIPinchGestureRecognizer) {

var lastScale:CGFloat = 1.0

    if let view = recognizer.view as? UITextView {

        if (recognizer.state == .began) {
            lastScale = 1.0
        }

        let scale = 1.0 - (lastScale - recognizer.scale)

        view.transform = CGAffineTransform(scaleX: scale, y: scale)
        view.font = UIFont.systemFont(ofSize: 40 * scale)

        lastScale = recognizer.scale

    }
}
2

2 Answers

2
votes

The variable lastScale will always be 1 because this method is deleted out of memory once it is used, until it is called again. Therefore, lastScale will always reset to 1. On top of that, you have recognizer.state == began and setting lastScale = 1 which means that everytime a new touch is called, lastscale = 1.

What you should be doing is creating a global variable, not local variable, and adjusting that scale. This will allow it to not reset back to 1 everytime. Also, don’t ever reset lastScale unless you press some reset function. Think about it - why would you want to reset your lastScale after it is set?

0
votes

In swift 5, you can just do this:

@objc func pinchHandler(_ sender: UIPinchGestureRecognizer) {
    guard let view = sender.view else { return }
    view.transform = view.transform.scaledBy(x: sender.scale, y: sender.scale)
    sender.scale = 1
}