将标注添加到,一点
和一点
,它们都融合在一起——这是一个有趣的挑战!
第一步是实现
无论如何,这里最主要的是重用视图以提高性能。请记住,创建视图的成本很高,因此最好创建少量视图并根据需要对其进行回收——只需更改文本标签,而不是每次都销毁并重新创建它们。
MapKit为我们提供了一个很好而简单的API,用于处理视图重用:我们创建所选择的字符串标识符,然后在地图视图上调用
如果确实返回
我们不在 SwiftUI 中,这意味着我们无法使用
像UIKit和MapKit中的所有委托方法一样,下一个名称很长。因此,最好的办法是进入
完成后,对其进行编辑:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { // 这是我们视图重用的唯一标识符 let identifier = "Placemark" // 试图找到一个我们可以回收的视图 var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) if annotationView == nil { // 我们找不到一个;创建一个新的 annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) // 允许它显示弹出信息 annotationView?.canShowCallout = true // 将信息按钮附加到视图 annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } else { // 我们有一个重用的视图,所以给它新的标注 annotationView?.annotation = annotation } // 无论是新视图还是复用视图,都将其返回 return annotationView } |
那还行不通,因为即使我们将
1 | newLocation.title = "Example location" |
如果您现在运行该应用程序,则会发现您可以通过按 + 按钮放置大头针,然后点击大头针以显示标题——以及右侧的小“i”按钮。使按钮发挥作用是乐趣所在,尽管对“乐趣”有非常特定的定义。
事情一开始就很简单:我们将在
1 2 | @Binding var selectedPlace: MKPointAnnotation? @Binding var showingPlaceDetails: Bool |
我更喜欢将所有
拥有这些额外的属性意味着我们需要调整
1 2 3 4 5 6 | MapView( centerCoordinate: .constant(MKPointAnnotation.example.coordinate), selectedPlace: .constant(MKPointAnnotation.example), showingPlaceDetails: .constant(false), annotations: [MKPointAnnotation.example] ) |
请记住要根据您在
在 ContentView.swift 中,我们需要做很多相同的事情,首先需要传递
1 2 | @State private var selectedPlace: MKPointAnnotation? @State private var showingPlaceDetails = false |
现在,我们可以更新其
1 2 3 4 5 | MapView(centerCoordinate: $centerCoordinate, selectedPlace: $selectedPlace, showingPlaceDetails: $showingPlaceDetails, annotations: locations) .edgesIgnoringSafeArea(.all) |
当
首先将以下
1 2 3 4 5 6 7 8 | .alert(isPresented: $showingPlaceDetails) { Alert(title: Text(selectedPlace?.title ?? "Unknown"), message: Text(selectedPlace?.subtitle ?? "Missinplace information."), primaryButton: .default(Text("OK")), secondaryButton: .default(Text("Edit")) { // edit this place }) } |
最后,我们需要更新·MapView·,以便为标注点击“i”按钮来设置
该方法的重要部分称为
现在将此方法添加到
1 2 3 4 5 6 7 8 9 | func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { guard let placemark = view.annotation as? MKPointAnnotation else { return } parent.selectedPlace = placemark parent.showingPlaceDetails = true } |
完成此步骤后,我们的项目的下一步已完成,因此请立即运行,您应该可以放置图钉,点击它以显示更多信息,然后按``i''按钮以显示警报
译自 Customizing MKMapView annotations