I have use @EnvironmentObject in my source code, but it doesn't work correctly.
it's just my code:
import Foundation
import MapKit
class Configure: ObservableObject
{
@Published var mapType = MKMapType.satellite
}
I have the Configure object in the userData:
class UserData: ObservableObject
{
@Published var configure: Configure
}
And use the configure object in the MapHome:
struct MapHome: View
{
@EnvironmentObject var userData: UserData
NavigationView
{
ZStack
{
MapView(mapViewState: mapViewHomeState)
.edgesIgnoringSafeArea(.all)
}
Button(action: {
switch self.userData.configure.mapType
{
case .hybrid:
self.userData.configure.mapType = .standard
case .standard:
self.userData.configure.mapType = .satellite
case .satellite:
self.userData.configure.mapType = .hybrid
default:
self.userData.configure.mapType = .standard
}
}
)
{
if self.configure.mapType == .hybrid
{
Image("HybridIcon")
}
else if self.configure.mapType == .standard
{
Image("StandardIcon")
}
else if self.configure.mapType == .satellite
{
Image("SatelliteIcon")
}
}
}
}
MapView is just like that:
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable
{
@ObservedObject var configure: Configure
func makeUIView(context: Context) -> MKMapView
{
return MKMapView(frame: .zero)
}
func updateUIView(_ view: MKMapView, context: Context)
{
//Set the map type
view.mapType = configure.mapType
}
}
Whe I click the button, the source code has go to MapView(mapViewState: mapViewHomeState).edgesIgnoringSafeArea(.all) , but not call MapView.updateUIView ! So, the map view doesn't refresh with the MKMapType!
What's wrong with my code? How could I do with it? Thanks very much!