【问题标题】:Pass data between UIViewRepresentable and SwiftUI在 UIViewRepresentable 和 SwiftUI 之间传递数据
【发布时间】:2022-01-23 03:12:26
【问题描述】:

我在我的应用程序中使用 Google 地图。该应用程序在地图上显示 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) { }
}

【问题讨论】:

    标签: ios swift google-maps swiftui


    【解决方案1】:

    你已经对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
    

    【讨论】:

    • 成功了...非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2020-04-05
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多