Edit:
MapViews have the ability to show locations by adding pins (or custom views) to the map. I am attempting the simplest version of customization, where I am just trying to replace the default popup view (Title, Subtitle, Info symbol (i with a circle around it)) with a custom view.
Using a MKMapView from SwiftUI requires using a UIViewRepresentable class with a coordinator to handle its delegate, because MKMapView is a UIKit class, not a SwiftUI struct.
In a UIViewController, I could add a view (or a tableviewcontroller's main view even) as a subview to the annotationView. My question is how to do that using a native SwiftUI struct View.
I am trying to add a custom detailCalloutAccessoryView to a MKPinAnnotation (MKAnnotationView)
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
addDropDown(annotationView: annotationView)
}
Here's are two attempts at writing addDropDown()
:
func addDropDown(annotationView: UIView?) {
guard let annotationView = annotationView as? MKPinAnnotationView else { return }
// This is a UIKit UITableViewController Instance
let tvc = RandomCapitalDropDown(nibName: nil, bundle: nil)
annotationView.addSubview(tvc.view)
// error: Cannot convert value of type 'MKPinAnnotationView' to expected argument type 'UIViewController?'
tvc.didMove(toParent: annotationView)
tvc.view.leadingAnchor.constraint(equalTo: annotationView.leadingAnchor).isActive = true
tvc.view.trailingAnchor.constraint(equalTo: annotationView.trailingAnchor).isActive = true
tvc.view.topAnchor.constraint(equalTo: annotationView.topAnchor).isActive = true
tvc.view.bottomAnchor.constraint(equalTo: annotationView.bottomAnchor).isActive = true
}
// This is for a SwiftUI Struct called `PinDropDown`
func addDropDown(annotationView: UIView?) {
guard let annotationView = annotationView as? MKPinAnnotationView else { return }
let child = UIHostingController(rootView: PinDropDown(gameMode: .byContinent(continent: 0)))
child.view.translatesAutoresizingMaskIntoConstraints = false
child.view.frame = parent.view.bounds
// parent is UIViewRepresentable, so there is no view - this won't work
parent.view.addSubview(child.view)
// same issue
parent.addChild(child)
}
I have reviewed: SwiftUI UIViewRepresentable and Custom Delegate and Access controller method from inside a model and How to find the frame of a swiftui uiviewrepresentable none of these answered my question.