Skip to content

Instantly share code, notes, and snippets.

@gunantosteven
Last active March 4, 2025 10:32
Show Gist options
  • Save gunantosteven/052cf9d13c031895382b9a140f11a6f2 to your computer and use it in GitHub Desktop.
Save gunantosteven/052cf9d13c031895382b9a140f11a6f2 to your computer and use it in GitHub Desktop.
Double Tap Zoom to The Tap Location Swift 5 iOS 13
@objc func handleDoubleTap(_ recognizer: UITapGestureRecognizer) {
let scale = min(scrollView.zoomScale * 2, scrollView.maximumZoomScale)
if scale != scrollView.zoomScale { // zoom in
let point = recognizer.location(in: imageView)
let scrollSize = scrollView.frame.size
let size = CGSize(width: scrollSize.width / scrollView.maximumZoomScale,
height: scrollSize.height / scrollView.maximumZoomScale)
let origin = CGPoint(x: point.x - size.width / 2,
y: point.y - size.height / 2)
scrollView.zoom(to:CGRect(origin: origin, size: size), animated: true)
} else if scrollView.zoomScale == 1 { zoom out
scrollView.zoom(to: zoomRectForScale(scale: scrollView.maximumZoomScale, center: recognizer.location(in: imageView)), animated: true)
}
}
func zoomRectForScale(scale: CGFloat, center: CGPoint) -> CGRect {
var zoomRect = CGRect.zero
zoomRect.size.height = imageView.frame.size.height / scale
zoomRect.size.width = imageView.frame.size.width / scale
let newCenter = scrollView.convert(center, from: imageView)
zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0)
zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0)
return zoomRect
}
@fl034
Copy link

fl034 commented Jan 17, 2024

Thanks for your gist. Helped me a lot. I improved it a bit (see my fork). E.g. Scrolling out is as easy as:

scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment