在 Swift 中将 ARView 传递给 Coordinator

问题描述 投票:0回答:1

我正在尝试将 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?

swift swiftui arkit coordinator-pattern
1个回答
2
投票

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

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
}
© www.soinside.com 2019 - 2024. All rights reserved.