Simply I have UIScrollView
with one view for zooming inside that view: UIImageView
.
This is how it looks when I just display the image:
When I pinch:
and when I swipe down after pinch:
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
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With