簡體   English   中英

在 UIViewRepresentable 和 SwiftUI 之間傳遞數據

[英]Pass data between UIViewRepresentable and SwiftUI

我在我的應用程序中使用谷歌地圖。 該應用程序在 map 上顯示 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM