5

Simply I have UIScrollView with one view for zooming inside that view: UIImageView.

This is how it looks when I just display the image:

enter image description here

When I pinch:

enter image description here

And when I swipe down after pinch:

enter image description here

And now I have black space I do not want to see. Is there a way to set some offsets and prevent from scrolling far after the image?

In code I simply use:

//MARK: - UIScrollViewDelegate

public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return photoImageView
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

1 Answers1

3

Simply implement UIScrollViewDelegate:

//MARK: - UIScrollViewDelegate

public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return photoImageView
}

public func scrollViewDidZoom(_ scrollView: UIScrollView) {

    let imageViewSize = photoImageView.frame.size
    let scrollViewSize = scrollView.bounds.size

    let verticalPadding = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0
    let horizontalPadding = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0

    if verticalPadding >= 0 {
        scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
    } else {
        scrollView.contentSize = imageViewSize
    }
}

and prepare view on viewDidLoad:

private func setupInitialView() {

    photoImageView.sizeToFit()

    let imageViewSize = photoImageView.bounds.size
    let scrollViewSize = scrollView.bounds.size
    let widthScale = scrollViewSize.width / imageViewSize.width
    let heightScale = scrollViewSize.height / imageViewSize.height

    scrollView.minimumZoomScale = min(widthScale, heightScale)
    scrollView.setZoomScale(scrollView.minimumZoomScale, animated: false)

    scrollViewDidZoom(scrollView)
}
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
  • Cheers Up! thank you for sharing your solution, it works fine for me, so I suggest to accept it. – Ahmad F Apr 05 '17 at 14:23
  • 1
    Hello! I know this is an old question, but for me code is not working. Any chance you can show your constraints? cz let imageViewSize = photoImageView.bounds.size will write here not an image size but imageView size == fullscreen (from your comments). I have the same case as you, but for me this solution isn't working. Thanks – Vlad Pulichev Oct 02 '18 at 12:36