Alvin Varghese Alvin Varghese - 1 year ago 113
Swift Question

Resizing UIView using UIPinchGestureRecognizer

I have this code which handles the pinch gesture and gets the scale value and passing to the


func pinchedOnView(gesture : UIPinchGestureRecognizer) {

switch gesture.state
case UIGestureRecognizerState.began:

self.resizableView.updateViewBounds(scale: gesture.scale , initialBounds: self.resizableView.bounds)

case UIGestureRecognizerState.changed :

self.resizableView.updateViewBounds(scale: gesture.scale, initialBounds: self.resizableView.bounds)

default : ()

So this function takes the input scale finds the corresponding frame and updates the view frame.

public func updateViewBounds(scale : CGFloat,initialBounds : CGRect) {

let zt = CGAffineTransform(scaleX: scale, y: scale)
let tempBounds = initialBounds.applying(zt)

if tempBounds.width < UIScreen.main.bounds.width - 20 && tempBounds.height < UIScreen.main.bounds.height - 20 {

if tempBounds.height > 300 || tempBounds.width > 300 {
self.bounds = tempBounds
else {


Yeah this function works properly, but it is very fast. Yes as we know that
returns each and every fraction of values.

I want the user to see a very proper view resizing, I don't want to update the view for every fraction of value. Any thoughts?

Answer Source

The problem is due to you are scaling the scaled version of the view bound in each sub sequence step using the relative scale respect to the original view bounds.

I think you need to store the initial view bounds of the targeted view at .begin and use this value to call the updateViewBounds. Another way would be setting gesture.scale = 1.0 at the end of your gesture handler function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download