Swift: 将 ARView 传递给 Coordinator

Swift: pass ARView to Coordinator

真的坚持这一点。 我正在尝试将 ARView 从 MakeUIView 传递到 makeCoordinator 我真的需要这个来在 @objc func handleTap

中使用 ARView
struct ARViewContainer: UIViewRepresentable{
func makeUIView(context: Context) -> ARView {
        
        let myARView = ARView(frame: .zero)
        //...config and things….
        let tapGesture = UITapGestureRecognizer(target: context.coordinator, action: #selector(context.coordinator.handleTap(_:)))
        myARView.addGestureRecognizer(tapGesture)
        return myARView
        
    }
func makeCoordinator() -> Coordinator {
        Coordinator("whatshouldiusehere", self.$focusObject, self.$focusName)
    }
    class Coordinator: NSObject {
            private let view: ARView
        private var object: Binding<Entity?>
    private var objectname: Binding<String?>
        init(_ view: ARView, _ obj: Binding<Entity?>, _ objname: Binding<String?>) {
            self.objectname = objname
                self.object = obj
                self.view = view
                super.init()
            }
        @objc func handleTap(_ sender: UIGestureRecognizer? = nil) {
            guard let touchInView = sender?.location(in: view) else {
              return
            }
            guard let hitEntity = view.entity(at: touchInView) else {return}
            //doing something with object here, assigning to @Binding for example

        }
    }
}

我无法将 myARView = ARView(frame: .zero) 移到 makeUIView 之外,因为我正在使用 SwiftUI 并且每次变量更改时它都会启动。 但是我怎么能以任何方式通过它呢? 或同时使用 ARView 访问 Binding 的任何其他选项。

协调器可通过上下文使用,因此您可以通过 属性 注入它,例如

struct ARViewContainer: UIViewRepresentable{
func makeUIView(context: Context) -> ARView {
        
        let myARView = ARView(frame: .zero)
        //...config and things….
        let tapGesture = UITapGestureRecognizer(target: context.coordinator, action: #selector(context.coordinator.handleTap(_:)))
        myARView.addGestureRecognizer(tapGesture)
       
        context.coordinator.view = myARView     // << inject here !!

        return myARView
        
    }
func makeCoordinator() -> Coordinator {
        Coordinator(self.$focusObject, self.$focusName)
    }
    class Coordinator: NSObject {
            var view: ARView?        // << optional initially

        private var object: Binding<Entity?>
        private var objectname: Binding<String?>
        
        init(_ obj: Binding<Entity?>, _ objname: Binding<String?>) {
                self.objectname = objname
                self.object = obj
                super.init()
            }

    // ... other code update accordingly
}