How to Zoom in on a scroll view in swift 4?

1.1k Views Asked by At

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
}

}
1

There are 1 best solutions below

0
DonMag On

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