你好,我需要在用户使用 swiftUI 在 UIImageView 中双击或捏住图像时,图像处于缩放模式。例如如果用户从UICollectionView中选择图像,则UIImageView中也会出现同样的图像,如果用户滑动UIImageView,则会出现UICollectionView中的图像。
这是一个有点棘手的。
你需要有一个 UIScrollView
的缩放功能,并使其在SwiftUI中可用。
struct ZoomableImageView: UIViewRepresentable {
var configuration = { (scrollView: UIScrollView, imageView: UIImageView) in } // To forwarding configuration
let zoomableImageViewDelegate = ZoomableImageViewDelegate() // Outsourcing the delegate to an NSObject object
func makeUIView(context: UIViewRepresentableContext<Self>) -> UIScrollView {
let scrollView = UIScrollView()
scrollView.delegate = zoomableImageViewDelegate
let imageView = zoomableImageViewDelegate.imageView
scrollView.addSubview(imageView)
imageView.frame = scrollView.frame
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return scrollView
}
func updateUIView(_ uiView: UIScrollView, context: UIViewRepresentableContext<Self>) { configuration(uiView, zoomableImageViewDelegate.imageView) }
}
这两个属性是需要的,并用注释来描述。
然后实现桥代表类。
class ZoomableImageViewDelegate: NSObject & UIScrollViewDelegate {
let imageView = UIImageView()
func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView }
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
scrollView.setZoomScale(1, animated: true)
}
}
那就像正常使用一样 View
:
struct ZoomingImageScrollView_Previews: PreviewProvider {
static var previews: some View {
ZoomableImageView { scrollView, imageView in
scrollView.minimumZoomScale = 1
scrollView.maximumZoomScale = 10
imageView.image = UIImage(systemName: "square")
imageView.contentMode = .scaleAspectFit
}
.previewLayout(.fixed(width: 319, height: 136))
}
}