UITapGestureRecognizer not working in TVOS

50 Views Asked by At

This is my code in SwiftUI + UIKit, I am trying to detect when the user is tapping on the D-pad, but this code doesn't seem to work. Can some help me or at least share some leads to solve this issue?

import SwiftUI
import UIKit

struct ContentView: View {
    struct IdentifiablePoint: Identifiable {
        let id = UUID()
        let point: CGPoint
    }

    @State var identifiablePoints: [IdentifiablePoint] = [IdentifiablePoint(point: CGPoint(x: 0, y: 0)), IdentifiablePoint(point: CGPoint(x: 50, y: 50))]
    var body: some View {
        return ZStack(alignment: .topLeading) {
            Background { location in
                // Convert CGPoint to IdentifiablePoint before appending
                let newPoint = IdentifiablePoint(point: location)
                self.identifiablePoints.append(newPoint)
            }
            .background(Color.white)
            ForEach(self.identifiablePoints) { identifiablePoint in
                Color.blue
                    .frame(width: 50, height: 50, alignment: .center)
                    .offset(CGSize(width: identifiablePoint.point.x, height: identifiablePoint.point.y))
            }
        }
    }
}

struct Background: UIViewRepresentable {
    var tappedCallback: (CGPoint) -> Void

    func makeUIView(context: UIViewRepresentableContext<Background>) -> UIView {
        let v = UIView(frame: .zero)
        let gesture = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.tapped))
        v.addGestureRecognizer(gesture)
        return v
    }

    class Coordinator: NSObject {
        var tappedCallback: (CGPoint) -> Void
        init(tappedCallback: @escaping ((CGPoint) -> Void)) {
            self.tappedCallback = tappedCallback
        }

        @objc func tapped(gesture: UITapGestureRecognizer) {
            let point = gesture.location(in: gesture.view)
            self.tappedCallback(point)
        }
    }

    func makeCoordinator() -> Background.Coordinator {
        return Coordinator(tappedCallback: self.tappedCallback)
    }

    func updateUIView(_ uiView: UIView,
                      context: UIViewRepresentableContext<Background>) {}
}

I am trying to detect when the user is tapping on the D-pad, but this code is not working.

0

There are 0 best solutions below