I want to pass the name of the selected annotation to another view called UserView, this is my code:
struct Maps: View {
@State private var showUserView = false
@ObservedObject var locationFetcher = LocationFetcher()
var body: some View {
ZStack(alignment: .bottom) {
MapView(annotations: locationFetcher.locations, showUserView: $showUserView)
.ignoresSafeArea()
if showUserView {
UserView()
.transition(.move(edge: .bottom))
.animation(.easeInOut)
}
}
}
}
struct MapView: UIViewRepresentable {
let annotations: [MKPointAnnotation]
@Binding var showUserView: Bool
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView(frame: .zero)
mapView.delegate = context.coordinator
mapView.showsUserLocation = true
mapView.userTrackingMode = .followWithHeading
mapView.mapType = .hybridFlyover
let region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 0, longitude: 0),
span: MKCoordinateSpan(latitudeDelta: 180, longitudeDelta: 360))
mapView.setRegion(region, animated: false)
mapView.showsBuildings = true
mapView.addAnnotations(annotations)
// Add gesture recognizer to handle annotation taps
let gestureRecognizer = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.annotationTapped))
mapView.addGestureRecognizer(gestureRecognizer)
return mapView
}
func updateUIView(_ mapView: MKMapView, context: Context) {
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotations(annotations)
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, MKMapViewDelegate {
let parent: MapView
init( parent: MapView) {
self.parent = parent
}
// Handle annotation taps by toggling showUserView
@objc func annotationTapped() {
parent.showUserView.toggle()
}
func mapView( mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let annotation = annotation as? MKPointAnnotation else {
return nil
}
let identifier = "CustomAnnotation"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
annotationView?.image = UIImage(named: "first.png")
} else {
annotationView?.annotation = annotation
}
return annotationView
}
}
}
This is what I tried:
- Added this call to the Maps struct:
UserView(selectedAnnotationTitle: $selectedAnnotationTitle)
- I updated the annotationTapped function:
@objc func annotationTapped(sender: UITapGestureRecognizer) {
if let annotationView = sender.view as? MKAnnotationView, let annotation = annotationView.annotation {
let annotationTitle = annotation.title ?? ""
parent.showUserView = true
parent.selectedAnnotationTitle = annotationTitle!
}
}
- I added this to MapView:
@State var selectedAnnotationTitle = ""
When I run the updated code, the annotations I get from another struct are not displayed.