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.
First you must ensure your image view is inside a scroll view.
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:
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.
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
}
}
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.