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

3
我正在开发一个使用MapKit/Swift 4的地图,其中有很多注释。用户可以使用Picker View选择他想要的注释(仅限1个),并且该注释将被调用(就像他按下了它一样)。如果更容易的话,我们可以考虑改变这个注释点的颜色。关键是在众多注释中突出显示此特定注释。在一些搜索后,我找到了这个函数。
func selectAnnotation(_ annotation: MKAnnotation, animated: Bool)

我已经实现了以下函数:

function test():

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
}

2
你可能已经给地图视图添加了注释,是吗?只需调用上述函数,并将其中一个注释作为参数传递进去即可。 - dalton_c
是的,确实如此。但这就是我的观点。我怎么能传递我的一个注解呢?我需要使用什么引用?实际上,我正在寻找一个例子。 - Hugo75
你会贴一些你的代码吗?比如用于添加注释的代码,或者你的选取器代码? - dalton_c
1个回答

4
您可以使用mapViewannotations属性来实现此功能。大致上,在您的视图控制器中,您需要编写以下代码:
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是您的视图控制器的实例变量,并且选择器视图的数据源和委托设置为您的视图控制器。我不对选择器视图或任何内容进行任何框架设置,因此您需要自行实现所有内容。

太好了!谢谢。为什么我需要 func beginAnnotationSelection() 这个函数? - Hugo75
该函数只是一个占位符,用于触发选择器视图的出现。它对实际功能并不必要。 - Jumhyn
我只是在寻找一种方法来做这件事! - Hugo75
有没有办法按字母顺序对注释进行排序? - Hugo75
你可以使用Array.sort和自定义的比较闭包。查看苹果的文档以了解如何实现这一点。 - Jumhyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接