How to Update UIviewrepresentable with Observableobject

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



Leave a reply



Submit