How to update UIViewRepresentable with ObservableObject
To make sure your ObservedObject
does not get created multiple times (you only want one copy of it), you can put it outside your UIViewRepresentable
:
import SwiftUI
import MapKit
struct ContentView: View {
@ObservedObject var dataSource = DataSource()
var body: some View {
MyView(locationCoordinates: dataSource.locationCoordinates, value: dataSource.value)
}
}
class DataSource: ObservableObject {
@Published var locationCoordinates = [CLLocationCoordinate2D]()
var value: Int = 0
init() {
Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { timer in
self.value += 1
self.locationCoordinates.append(CLLocationCoordinate2D(latitude: 52, longitude: 16+0.1*Double(self.value)))
}
}
}
struct MyView: UIViewRepresentable {
var locationCoordinates: [CLLocationCoordinate2D]
var value: Int
func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}
func updateUIView(_ view: MKMapView, context: Context) {
print("I am being called!")
let newestCoordinate = locationCoordinates.last ?? CLLocationCoordinate2D(latitude: 52, longitude: 16)
let annotation = MKPointAnnotation()
annotation.coordinate = newestCoordinate
annotation.title = "Test #\(value)"
view.addAnnotation(annotation)
}
}
How to update UIViewRepresentable map through Binding and ObservedObject
At the moment when I posted the question I found the problem.
I've forgot to mark the selectedRegion variable as @Published in the TrackingOnMapViewModel.
@Published var selectedRegion: MKCoordinateRegion = MKCoordinateRegion
Related Topics
Swift Override Static Method Compile Error
Errors Encountered While Discovering Extensions: Error Domain=Pluginkit Code=13 "Query Cancelled"
Easiest Way to Truncate Float to 2 Decimal Places
Swift: Binary Operator '==' Cannot Be Applied to Operands of Type "Protocol"
How to Create a Pulse Effect on an Skspritenode
Edit Templates Authentication Firebase
How to Spin and Add a Linear Force to an Entity Loaded from Reality Composer
Vapor 3 Postgresql Crud Without Requests Http
How to Use Publishers.Combinelatest to Get 1 Publisher
How to Update UIviewrepresentable with Observableobject
Cannot Assign to Value: 'self' Is Immutable
Why I Can Not Use Setvalue for Dictionary
"The Requested Snapshot Version Is Too Old." Error in Firestore
Crash Casting Wknsurlrequest As? Other Type
Window Title Bar Appears Transparent Issue (Not Really Transparent)