Pinch To Zoom Images Swift Tutorial

By Eddy Chung

You want to allow your user to zoom in on images in your app.

Perhaps you have a photo gallery or are showcasing some products. Don’t worry, it’s pretty simple to implement.

How To Get Pinch To Zoom Images In Swift

First you must ensure your image view is inside a scroll view.

scrollinimage

If it isn’t already you can select your image view and then embed it in a scroll by using the embed in button in the interface builder: scrollinimage_3

Once you have that set up, create IBOutlets for both your image view and your scroll view.

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var image: UIImageView!

Next make sure your view controller subclasses UIScrollViewDelegate:

class ViewController: UIViewController, UIScrollViewDelegate {

Now in your viewDidLoad() function, set the zoom scale and the delegate:

override func viewDidLoad() {
    super.viewDidLoad()
    scrollView.delegate = self
    scrollView.minimumZoomScale = 1.0
    scrollView.maximumZoomScale = 10.0
}

Finally set the view for zooming in:

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

Now run your application and you should be able to zoom in on your image using a pinch gesture.

pinchtozoom

Full Code

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var image: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        scrollView.delegate = self
        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 10.0
    }

    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return image
    }
}
If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts