我有一个使用MKMapView的MapView,还有一个HomeView,其中显示了MapView和ResultsCarouselView(现在为方便起见,将其替换为Circle)。
如果我有一个可观察对象来管理此HomeView的状态,是否可以从协调器使用它?例如,我从协调器中的HomeState调用的任何内容都不会更新HomeView:
MapCoordinator
final class MapCoordinator: NSObject, MKMapViewDelegate {
@ObservedObject var homeState = HomeState()
// other code, init, etc.
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
self.homeState.setUserLocated(true)
}
}
HomeState:
class HomeState: NSObject, ObservableObject {
@Published var userLocated = false
func setUserLocated(_ value: Bool) {
self.userLocated = value // debugger comes here, but is this another instance or something?
}
}
HomeView:
struct HomeView: View {
@ObservedObject var homeState = HomeState()
var body: some View {
ZStack(alignment: .bottom) {
MapView()
if (homeState.userLocated) {
Circle() // this doesn't show up
}
}
}
}
答案 0 :(得分:0)
struct MapView: UIViewRepresentable {
@ObservedObject var homeState = HomeState()
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
self.parent.homeState.setUserLocated(true)
}
}
}
您可以使用parent
中的Coordinator
变量来修改任何@State
或@ObservableObject
,例如您的HomeState @ObservedObject