0

I have noticed an issue where I resize a View, but the bounds do not appear to change (so after pinching a view you have to use the edge of a UIView to pinch further)

@IBAction private func handlePinch(_ sender: UIPinchGestureRecognizer) {
    if let view = sender.view {
        view.transform = view.transform.scaledBy(x: sender.scale, y: sender.scale)
        sender.scale = 1
    }
}

I found a likely stackoverflow answer iphone uiview - resize frame to fit subviews that gave an extension to resize to fit subviews, but there is no observable difference in the behavior of the objects.

@IBAction private func handlePinch(_ sender: UIPinchGestureRecognizer) {
    if let view = sender.view {
        view.transform = view.transform.scaledBy(x: sender.scale, y: sender.scale)
        sender.scale = 1
    }
    self.resizeToFitSubviews()
}


extension UIView {
func resizeToFitSubviews() {
    let subviewsRect = subviews.reduce(CGRect.zero) {
        $0.union($1.frame)
    }
    let fix = subviewsRect.origin
    subviews.forEach {
        $0.frame.offsetBy(dx: -fix.x, dy: -fix.y)
    }
    frame.offsetBy(dx: fix.x, dy: fix.y)
    frame.size = subviewsRect.size
}

How can I make the pinch (and ultimately the handleRotate function with the same issue) work to adjust the bounds correctly?

stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47

2 Answers2

0

Changing the transform does not change bounds.

Please refer to the answer here: Does the bounds of a uiview change when a pinch gesture is used on it?

Rishabh
  • 465
  • 5
  • 14
0

For people looking for the answer, this has been really tricky to find. Rishabh linked to a post from 2011 with no explanation, and it also did not work without making further changes.

If you are changing bounds you no longer need to apply a view.transform.scaledBy(x: sender.scale, y: sender.scale)

but rather need to change the bounds using similar code

        self.bounds = self.bounds.applying(view.transform.scaledBy(x: sender.scale, y: sender.scale))

so the complete code can be:

@IBAction private func handlePinch(_ sender: UIPinchGestureRecognizer) {
    if let view = sender.view {
        self.bounds = self.bounds.applying(view.transform.scaledBy(x: sender.scale, y: sender.scale))
        sender.scale = 1
    }
        self.resizeToFitSubviews()
}
stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47