简体   繁体   中英

Pass data between UIViewRepresentable and SwiftUI

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM