更改@ State,@ Binding或@EnvironmentObject时不调用UIViewRepresentable.updateUIView(_:context :)

时间:2019-10-20 15:17:02

标签: ios swift state swiftui uiviewrepresentable

更改此视图及其父视图所依赖的ObservableObject时,不会调用UIViewRepresentable.updateUIView。

我有一个带有“ @State var locationManager:LocationManager”的GameView,该游戏作为绑定传递给我的MapView。 MapView符合UIViewRepresentable协议。除其他外,LocationManager符合ObservableObject的要求,并具有以下与一致性相关的代码:

ex_id<-li[[9]]
df_ex_id <- as.data.frame(unlist(map(ex.id,5)))

我认为每次LocationManager.lastKnownLocation更改时,都必须更新GameView,因此必须更新MapView。在实践中,当我每个主页按钮退出应用程序时,我只会看到MapView.updateUIView()被调用。此时,控件进入了updateUIView(),当我再次打开该应用程序时(不是compile-install-run),我得到了更新。在展示GameView()之后不久,也会发生这种情况。

我是否了解SwiftUI的工作方式有误还是存在一些错误?如何正确处理?

name_exid <- for (i in li$name) {
print(li$name) + print(li$exerciseIdList[[1]])  
}

我希望每一个Tim LocationManager.lastKnownLocation都发生变化,就会调用MapView.updateUIView()。实际上,只有在我按主页按钮退出应用程序(然后再次输入)时,才会发生通话

1 个答案:

答案 0 :(得分:0)

像这样更改MapView

struct MapView: UIViewRepresentable {
  @State var locationManager = LocationManager()

  func makeUIView(context: Context) -> GMSMapView{
    let view = GMSMapView(frame: .zero)
    ...
    willAppear(context)
    return view
  }

  func updateUIView(_ mapView: GMSMapView, context: Context) { ... }

  func makeCoordinator() -> MapView.Coordinator {
    return Coordinator()
  }

  static func dismantleUIView(_ uiView: GMSMapView, coordinator: MapView.Coordinator) {
    coordinator.cancellable.removeAll()
  }

  class Coordinator {
    var cancellable = Set<AnyCancellable>()
  }
}

extension MapView {
  func willAppear(_ context: Context) {
    locationManager.didChange.sink{
      print("location: \($0)")
    }.store(in: &context.coordinator.cancellable)

    locationManager.startUpdating()
  }
}

我认为locationManager.startUpdating()locationManager.stopUpdating()这个方法需要调用另一个类。