编辑:
在SwiftUI中使用MKMapView需要使用带有协调器的UIViewRepresentable类来处理其委托,因为MKMapView是UIKit类,而不是SwiftUI结构。
在UIViewController中,我可以将一个视图(甚至是tableviewcontroller的主视图)添加为注释视图的子视图。我的问题是如何使用本机SwiftUI结构视图执行此操作。
我正在尝试将自定义detailCalloutAccessoryView添加到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)
}
这是两次尝试写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)
}
我评论了: SwiftUI UIViewRepresentable and Custom Delegate 和 Access controller method from inside a model 和 How to find the frame of a swiftui uiviewrepresentable 这些都没有回答我的问题。