Swift:将ARView传递给协调器

问题描述

真的坚持下去。 我正在尝试将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
}