【问题标题】:How programmatically select a specific annotation in Mapkit - Swift如何以编程方式在 Mapkit 中选择特定注释 - Swift
【发布时间】:2018-01-03 21:17:38
【问题描述】:

我正在使用 MapKit/Swift 4 开发地图,其中有很多注释。 用户可以使用 Picker View 选择他想要的注释(只有 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】:

您可以使用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() ?
  • 该函数只是一个占位符,用于在您的应用中触发选择器视图的外观。实际功能不需要。
  • !我只是想办法做到这一点!
  • 任何想法按字母顺序对注释进行排序?
  • 您可以将Array.sort 与自定义比较闭包一起使用。查看 Apple 的文档以了解如何执行此操作。
猜你喜欢
  • 1970-01-01
  • 2023-04-11
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
相关资源
最近更新 更多