简单地说,我有一个UIScrollView用于在该视图内部进行缩放:UI
ImageView.
当我捏:
当我在捏之后向下滑动时:
现在我有黑色的空间,我不想看到.有没有办法设置一些偏移并防止在图像后滚动很远?
在代码中我只使用:
//MARK: - UIScrollViewDelegate
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return photoImageView
}
最佳答案 只需实现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
}
}
并在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)
}