使用SwiftUI滚动放大多张图片 [关闭] [关闭]。

问题描述 投票:0回答:1

你好,我需要在用户使用 swiftUI 在 UIImageView 中双击或捏住图像时,图像处于缩放模式。例如enter image description here如果用户从UICollectionView中选择图像,则UIImageView中也会出现同样的图像,如果用户滑动UIImageView,则会出现UICollectionView中的图像。

swiftui pinchzoom
1个回答
0
投票

这是一个有点棘手的。

你需要有一个 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)
    }
}

Usage

那就像正常使用一样 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))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.