如何以编程方式在Mapkit - Swift中选择特定的注释

问题描述 投票:0回答:1

我正在MapKit / Swift 4中开发一个地图,我有很多注释。用户可以选择Picker查看他想要的注释(只有1个),并且将调用注释(就像他已经推动它一样)。如果更容易,我们可以考虑更改此注释点的颜色。关键点是在许多注释中突出显示这个特定的注释。

经过一番搜索,我发现了这个功能

func selectAnnotation(_ annotation: MKAnnotation, animated: Bool)

我已经实现了以下功能:

func selectPoints() {
    print("selectPoints called")
    let annotation1 = MKPointAnnotation()
    annotation1.coordinate = CLLocationCoordinate2D(latitude: 48.8596833, longitude: 2.3988939)
    annotation1.title = "Temple"
    annotation1.subtitle = "\(annotation1.coordinate.latitude), \(annotation1.coordinate.longitude)"
    mapView.addAnnotation(annotation1)

    mapView.selectAnnotation(annotation1, animated: true)
}

所以如果我创建一个新的注释,它是有效的,但我怎么能选择以前的注释点?但我没有任何想法或提示继续前进。

谢谢你的帮助。

编辑:输入注释的部分代码。

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if let annotation = annotation as? Artwork {

        let reuseId = "pin"
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)

        if pinView == nil {
            pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            pinView!.canShowCallout = true
            pinView!.isDraggable = false
            pinView!.calloutOffset = CGPoint(x: 0, y: 0)
            pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView

        }
        else {
            pinView!.annotation = annotation
        }

    }

    return nil
}
swift mapkit mkannotation mapkitannotation
1个回答
0
投票

您可以使用annotationsmapView属性执行此操作。作为一个粗略的轮廓,在视图控制器中你会得到一些像这样的代码:

func beginAnnotationSelection() {
    self.view.addSubview(self.pickerView)
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.mapView.annotations.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return self.mapView.annotations[row].title ?? "No title"
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    self.mapView.selectAnnotation(self.mapView.annotations[row], animated: true)
}

请注意,这假设mapViewpickerView是视图控制器的实例变量,并且选择器视图的数据源和委托被设置为视图控制器。我没有为选择器视图或任何东西做任何框架设置,所以你必须自己实现所有这些。

© www.soinside.com 2019 - 2024. All rights reserved.