3

真的坚持这一点。我正在尝试将 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 绑定的选项。

4

1 回答 1

0

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

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
}
于 2020-11-09T13:46:42.503 回答