在 UIViewRepresentable 和 SwiftUI 之间传递数据
Pass data between UIViewRepresentable and SwiftUI
我在我的应用程序中使用 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) { }
}
您已对 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
我在我的应用程序中使用 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) { }
}
您已对 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