【问题标题】:How to declare GMSMapViewDelegate on SwiftUI如何在 SwiftUI 上声明 GMSMapViewDelegate
【发布时间】:2020-05-14 23:49:58
【问题描述】:

我是 SwiftUI 的新手,正在尝试使用带有地图的 GoogleMapsApi 实施解决方案,用户可以在其中触摸地图并做事。为此,我知道必须实现委托,但我不知道如何使用 SwifUI 实现这一点。 Web 上有很多代码示例,使用 Swift 甚至 Objective C 时,但我在 SwifUI 上找不到。

这就是我所做的(我试图让这段代码尽可能简单):


struct GoogleMapsHomeView: UIViewRepresentable {

    func makeUIView(context: Self.Context) -> GMSMapView {

        let mapView = GMSMapView.map()

        return mapView

    }

    func updateUIView(_ mapView: GMSMapView, context: Context) {

    }

}

struct HomeView: View {

    var body: some View {
        GoogleMapsHomeView()
    }

}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}

谁能帮我为用户地图移动检测声明 GMSMapViewDelegate 和相关侦听器?

提前 10 倍寻求帮助。

【问题讨论】:

    标签: swiftui google-maps-sdk-ios


    【解决方案1】:

    常见的模式是使用协调器作为委托

    struct GoogleMapsHomeView: UIViewRepresentable {
    
        func makeUIView(context: Self.Context) -> GMSMapView {
    
            let mapView = GMSMapView.map()
            mapView.delegate = context.coordinator
            return mapView
    
        }
    
        func makeCoordinator() -> Coordinator {
           Coordinator(owner: self)
        }
    
        func updateUIView(_ mapView: GMSMapView, context: Context) {
        }
    
        class Coordinator: NSObject, GMSMapViewDelegate {
           let owner: GoogleMapsHomeView       // access to owner view members,
    
           init(owner: GoogleMapsHomeView) {
             self.owner = owner
           } 
    
             // ... delegate methods here
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-25
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      相关资源
      最近更新 更多