我在应用程序中使用谷歌地图。当地图视图被拖动一定距离时,该应用程序会在地图上显示POI标记,并从我的BE加载数据。我想将shoudlRefresh
值传递回ContentView,并要求用户再次刷新数据。
我已经使用@Binding在ContentView和UIViewRepresentable之间传递数据,但我不能通过Coordinator在映射委托中使用此@Binding var shouldRefresh
。
如果我试图通过协调器init()
将@Binding var传递给协调器,我会得到这两个错误
at POINT A -> Property 'self.mShouldRefresh' not initialized at implicitly generated super.init call
at POINT B -> self' used in property access 'mShouldRefresh' before 'super.init' call
仅相关代码:
struct MapsView: UIViewRepresentable {
@Binding var shouldRefresh: Bool
func makeUIView(context: Context) -> GMSMapView
func updateUIView(_ mapView: GMSMapView, context: Context)
{
func makeCoordinator() -> Coordinator {
Coordinator(owner: self, refresh: $shouldRefresh)
}
class Coordinator: NSObject, GMSMapViewDelegate {
let owner: MapsView
@Binding var mShouldRefresh: Binding<Bool>
var startPoint : CLLocationCoordinate2D?
var startRadius : Double?
init(owner: MapsView, refresh: Binding<Bool>) { // POINT A
self.owner = owner
self.mShouldRefresh = refresh // POINT B
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) { }
}
您已经对mShouldRefresh
进行了双重绑定
只需更改为
@Binding var mShouldRefresh: Bool
在init内部更改这个
self._mShouldRefresh = refresh
另一种方法是
// Other Code
var owner: MapsView
var mShouldRefresh: Binding<Bool>
init(owner: MapsView, refresh: Binding<Bool>) {
self.owner = owner
self.mShouldRefresh = refresh
}
// Other Code