I’m trying to use UIImageView
in my SwiftUI project. But the pinch gesture is not working. I tried several solutions that should work fine in UIKit.
struct UIImageViewRepresentable: UIViewRepresentable {
let image: UIImage?
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: UIImageViewRepresentable
init(_ parent: UIImageViewRepresentable) {
self.parent = parent
}
@objc func handlePinchGesture(_ sender: UIPinchGestureRecognizer) {
guard let view = sender.view else { return }
UIView.animate(withDuration: 0.3) {
let scaleResult = sender.view?.transform.scaledBy(x: sender.scale, y: sender.scale)
guard let scale = scaleResult, scale.a > 1, scale.d > 1 else { return }
sender.view?.transform = scale
sender.scale = 1
}
}
}
func makeUIView(context: Context) -> UIImageView {
let imageView = UIImageView()
imageView.image = image
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(UIPinchGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handlePinchGesture(_:))))
return imageView
}
func updateUIView(_ uiView: UIImageView, context: Context) {
uiView.image = image
}
}
struct ContentView: View {
var body: some View {
UIImageViewRepresentable(image: UIImage(named: "default"))
.frame(width: 300, height: 300)
.background(Color.gray)
.padding()
}
}
After adding the animate, the image do scaled but immediately back to the initial size. Why does this happen?