Search code examples
iosxcodesubviewpinchzoomuipinchgesturerecognizer

Scaling uivew scales its subview issue


i am having a container view with imageview and circleView with circle shape, on pinch gesture i want to scale imageview not the circleView with circle shape.

Below is my code

if(gestureRecognizer.state == .began || gestureRecognizer.state == .changed) {

        let currentScale: CGFloat = containerView.layer.value(forKeyPath: "transform.scale") as! CGFloat

        // Constants to adjust the max/min values of zoom
        let kMaxScale: CGFloat = 2.0
        let kMinScale: CGFloat = 1.0

        var newScale = 1 - (lastScale - gestureRecognizer.scale)
        // new scale is in the range (0-1)

        newScale = min(newScale, kMaxScale / currentScale)
        newScale = max(newScale, kMinScale / currentScale)
        containerView.transform = containerView.transform.scaledBy(x: newScale, y: newScale)

        lastScale = gestureRecognizer.scale
    }

On scaling container view imageView as well as circleView is getting scaled.

Anyone knows how to prevent subview from being scaled?


Solution

  • A view inherits it's frame of reference from it's superview. If you apply a transform to a view it affects the view and all it's superviews. It's like shrinking a piece of paper with a drawing on it. Of course the drawing shrinks if the paper shrinks.

    Don't make it a your other views subviews. Make them sibling views that you place on top of the view that's shrinking. That way they won't be affected.