![](/img/trans.png)
[英]iOS: Make function calls between UIViewRepresentable and View both ways, 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.