[英]How to navigate from mapkit annotation - SwiftUI/Xcode 11
我在 Xcode 11.1 和 SwiftUI 中使用 MapKit 來顯示帶有注釋的 map。 注釋有一個顯示標題的標注,以及右邊的CalloutAccessoryView 上的一個按鈕。 當用戶單擊 rightCalloutAccessoryView 按鈕時,我希望能夠導航到另一個視圖。
calloutAccessoryControlTapped function 中的 NavigationLink 不起作用。 在 SwiftUI 中應該怎么做? 任何幫助深表感謝!
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "AnnotationView")
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "AnnotationView")
}
let whiteImage = UIImage(named: "white")
annotationView!.image = whiteImage
annotationView?.isEnabled = true
annotationView?.canShowCallout = true
annotationView?.centerOffset = CGPoint(x: 0, y: -23)
let button = UIButton(type: .detailDisclosure)
annotationView?.rightCalloutAccessoryView = button
return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
@State var tapped = true
//ERROR: Property wrappers are not yet supported on local properties
NavigationLink(destination: DetailView(), isActive: $tapped) {EmptyView()}
//ERROR: Use of unrecognized identifier '$tapped'
}
希望現在還不算晚,但我遇到了同樣的問題。 我想出了一個解決方法,將 NavigationLink 與isActive:
一起使用。 首先在包含 SwiftUI MapView 的位置創建@State
變量,例如:
@State var isActive: Bool = false
@State var selectedAnnotation: MKAnnotation?
然后將 NavigationLink 與您的 SwiftUI MapView 分組,如下所示:
Group {
NavigationLink(destination: [relate your selectedAnnotation to your destination view], isActive: self.$isActive) {
EmptyView()
}
MapView(annotations: getAnnotations(), isClicked: self.$isActive, selectedAnnotation: self.$selectedAnnotation)
}
最后在你的 Coordinator/MKMapViewDelegate
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {}
你會想做這樣的事情:
self.view.isClicked = true
self.view.selectedAnnotation = view.annotation
請注意, view.annotation
中的view
是指annotationView view: MKAnnotationView
而self.view
是指var view: MapView
class Coordinator: NSObject, MKMapViewDelegate {
var view: MapView
init(_ control: MapView) {
self.view = control
}
func mapView(_ mapView: MKMapView, viewFor
annotation: MKAnnotation) -> MKAnnotationView? {}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {}
...
}
可能有更好的方法來做到這一點,但這有效!
注意:我創建了符合 UIViewRepresentable 的MapView
。
沒有mapView(...)
API 可以做到這一點。
你所做的就像
button.addTarget(self, action: #selector(self.buttonAction(_:)), for: .touchUpInside)
從您的按鈕獲得點擊。
這是來自 Apple 的一個很好的 API 設計,因為它讓您可以自由使用任意控件,包括包含多個任意控件的容器視圖。
將此問題視為“我如何以編程方式使用 UIButton?”。 在 MapKit 中使用UIButton
的事實並不是很相關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.