Last active
March 4, 2025 10:32
-
-
Save gunantosteven/052cf9d13c031895382b9a140f11a6f2 to your computer and use it in GitHub Desktop.
Double Tap Zoom to The Tap Location Swift 5 iOS 13
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)