Home > front end >  Pass data between UIViewRepresentable and SwiftUI
Pass data between UIViewRepresentable and SwiftUI

Time:12-22

I'm using Google maps in my application. The app shows POI markers on the map and load data from my BE when the mapview is dragged by certain distance. I want to pass the shoudlRefresh value back to ContentView and ask user to refresh the data again.

I've used @Binding to pass data between my ContentView and UIViewRepresentable but i cannot use this @Binding var shouldRefresh inside maps delegate through Coordinator.

If i try to pass this @Binding var to coordinator through coordinator init(), I'm getting these two error

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

Only relevant code:

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) { }
}

CodePudding user response:

You have given double binding to mShouldRefresh

Just change to

@Binding var mShouldRefresh: Bool

and inside the init change this

self._mShouldRefresh = refresh


Another way is

// Other Code
var owner: MapsView
var mShouldRefresh: Binding<Bool>

init(owner: MapsView, refresh: Binding<Bool>) {
    self.owner = owner
    self.mShouldRefresh = refresh
}
// Other Code
  • Related