0

My view controller programmatically creates several image views in a grid inside a scroll view. I want to be able to pinch to zoom in/out. I have pasted some similar code below which I found on stack overflow trying to do the same thing. The issue is that viewForZooming returns only one image. How do I get pinch to zoom to work for all of the image views in the scroll view? I just want to adjust the zoom scale of the scroll view as you pinch in/out.

Following code is what I have tried to achieve the required functionality:

class PhotoViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var image: UIImageView!
  
override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.minimumZoomScale = 1.0
    scrollView.maximumZoomScale = 6.0        
    scrollView.delegate = self 
}  
    
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return image
}

}
Saurabh
  • 745
  • 1
  • 9
  • 33
pat
  • 1
  • You have *"several image views in a grid inside a scroll view"* ... do you want to zoom an individual imageView, leaving the others at their original sizes? Or do you want to zoom the content of the scroll view as a whole? – DonMag Aug 14 '20 at 13:02
  • Zoom in on the content of the scroll view as a whole. My scroll view contains anywhere from 1-20 image views at a time – pat Aug 18 '20 at 14:40

1 Answers1

1

If you want to zoom multiple image views (or other UI elements) as a whole, you need to embed them in a UIView. Then, return that view in viewForZooming.

Here's a simple example:

enter image description here

The Yellow rectangle is a UIView, which I've connected via @IBOutlet as myContentView. It has 3 image views as subviews.

The scroll view has a red background, not seen here because myContentView is set to equal width and height to the scroll view frame (but you'll see it in the zoomed-out screen cap below).

Here's the code:

class MultiZoomViewController: UIViewController, UIScrollViewDelegate {
    
    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var myContentView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
    
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 6.0
        scrollView.delegate = self
        
    }

    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return myContentView
    }

}

and the results - start / zoomed out / zoomed in:

enter image description here

enter image description here

enter image description here

DonMag
  • 69,424
  • 5
  • 50
  • 86