Skip to content

Instantly share code, notes, and snippets.

@PetreVane
Last active January 24, 2020 17:24
Show Gist options
  • Save PetreVane/d38aac68c8d5a276c93697bbe21e0f87 to your computer and use it in GitHub Desktop.
Save PetreVane/d38aac68c8d5a276c93697bbe21e0f87 to your computer and use it in GitHub Desktop.
In order to do any kind of zooming, you need to implement a Scrollviewdelegate Protocol. This protocol contains a bunch of handy methods. The method we're after though, is viewForZooming (in: UIScrollView), which just sets the view to be zoomed. All you need to do is to return the view that you want to zoom from this method. If there are multip…
extension PhotoDetailsVC: UIScrollViewDelegate {
/// Returns the view that is expected to be zoomed
/// - Parameter scrollView: A view that allows the scrolling and zooming of its contained views.
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
/// Configures the zoom scale
/// - Parameter scrollViewSize: accepts the size of the scrollView bounds, as argument
func zoomParameters(_ scrollViewSize: CGSize) {
// gets the size of the image
let imageSize = imageView.bounds.size
// divides the scrollView size to ImageView size, and gets the minimum value
let widthScale = scrollViewSize.width / imageSize.width
let heightScale = scrollViewSize.height / imageSize.height
let minScale = min(widthScale, heightScale)
//sets the minimum value as starting zoom scale & minimum zoom scale
scrollView.minimumZoomScale = minScale
scrollView.maximumZoomScale = 3
scrollView.zoomScale = 1
}
}
/// Centers back the image when user Stops zooming out, so the image won't remain zoomed out
func centerImage() {
// gets the scrollView & imageView size
let scrollViewSize = scrollView.bounds.size
let imageViewSize = imageView.frame.size
/*
If the imageView size is smaller than the scrollView size, then substracts the size of the image from the size of the scrollView, and then divides the difference by 2.
Then this value (the difference) is set as distance (Insets) between the scrollView and image
*/
let horizontalSpace = imageViewSize.width < imageViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0
let verticalSpace = imageViewSize.height < imageViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0
// sets the UIInsets values
scrollView.contentInset = UIEdgeInsets(top: verticalSpace, left: horizontalSpace, bottom: verticalSpace, right: horizontalSpace)
}
/// Called to notify the view controller that its view is about to layout its subviews.
override func viewWillLayoutSubviews() {
centerImage()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment