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
}
}
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 inviewForZooming.Here's a simple example:
The Yellow rectangle is a
UIView, which I've connected via@IBOutletasmyContentView. It has 3 image views as subviews.The scroll view has a red background, not seen here because
myContentViewis 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:
and the results - start / zoomed out / zoomed in: