Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with offsets in UIScrollView zooming for UIImageview?

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 wanna 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
}
like image 410
Bartłomiej Semańczyk Avatar asked Oct 19 '22 01:10

Bartłomiej Semańczyk


1 Answers

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)
}
like image 146
Bartłomiej Semańczyk Avatar answered Nov 01 '22 09:11

Bartłomiej Semańczyk