Pinch To Zoom Images Swift Tutorial

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 and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts