SwiftUI:如何从UIViewRepresentable内部的协调器(MKMapView委托)中访问控制器?

时间:2020-03-13 15:10:53

标签: uikit swiftui

编辑:

MapViews可以通过向地图添加图钉(或自定义视图)来显示位置。我正在尝试最简单的自定义版本,在此我只是尝试用自定义视图替换默认的弹出视图(标题,字幕,信息符号(i周围有一个圆圈))。

在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 DelegateAccess controller method from inside a modelHow to find the frame of a swiftui uiviewrepresentable 这些都没有回答我的问题。

0 个答案:

没有答案