Search code examples
swiftswiftuiuiviewrepresentable

Swift UITapGestureRecognizer not calling


Pretty simple problem that is making out to be harder to solve than it should: My gesture is simple not calling, at all. I am using a uiviewrepresentable that is displayed inside of a zstack. If i add a .tapgesture{} to CameraView() directly it works just fine. But i need to get the tap position

public struct CameraView: UIViewRepresentable {
    @EnvironmentObject var ue: UserEvents
    public func makeUIView(context: Context) -> UIView {
        let view = UIView(frame: UIScreen.main.bounds)
        let focusGesture = UITapGestureRecognizer(target: self, action: #selector(context.coordinator.tapFocus(_:)))
        self.ue.cameraPreview = AVCaptureVideoPreviewLayer(session: ue.session)
        self.ue.cameraPreview.frame = view.frame
        self.ue.cameraPreview.videoGravity = ue.videoGravity
        self.ue.session.startRunning()
        view.isUserInteractionEnabled = true
        view.layer.addSublayer(self.ue.cameraPreview)
        focusGesture.numberOfTapsRequired = 1
        view.addGestureRecognizer(focusGesture)
        return view
    }
    
    public func updateUIView(_ uiView: UIViewType, context: Context) { }
    
    public func makeCoordinator() -> Self.Coordinator {
        return Coordinator()
    }
    
    public class Coordinator: NSObject {
        @objc public func tapFocus(_ sender: UITapGestureRecognizer) {
            print("tap")
        }
    }
}

Solution

  • The target should be the coordinator (which is a persistent entity, unlike the transient View), not self.

    let focusGesture = UITapGestureRecognizer(target: context.coordinator, action: #selector(context.coordinator.tapFocus(_:)))