如何从以前的比例开始捏捏缩放手势?

时间:2019-01-17 04:17:14

标签: ios swift

我正在尝试使用Pinch Gesture Recognizer来缩放UITextView,但是它始终以1.0的比例开始。 我尝试实现以下答案:
iOS Pinch Zoom Start from Previous Scale
UIPinchGestureRecognizer. Make zoom in location of fingers, not only center
Pinch gesture scale resetting to 1?

但我一定做错了,因为它每次仍会重置为1.0。这是我的代码:

@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 个答案:

答案 0 :(得分:2)

变量lastScale将始终为1,因为使用该方法后,该方法将从内存中删除,直到再次调用它为止。因此,lastScale将始终重置为1。最重要的是,您拥有recognizer.state == began并设置了lastScale = 1,这意味着每次调用新触摸时,lastscale = 1

您应该做的是创建一个全局变量,而不是局部变量,并调整该比例。这样一来,它就不会每次都重置为1。另外,除非您按下某些重置功能,否则切勿重置lastScale。想一想-为什么您要在设置lastScale后重设它?

答案 1 :(得分:0)

在 swift 5 中,你可以这样做:

@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
}