当聚合时如何显示MKAnnotation标注弹出窗口

3

我有一个TableView,用于在单击单元格时显示MapView注释标注。


在iOS 10中,我可以使用以下代码将MapView居中显示在注释上,然后显示它的标注:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let location = locations[indexPath.item]
    mapView.setCenter(location.coordinate, animated: true)
    mapView.selectAnnotation(location, animated: true)
}

locations是一个MKAnnotation数组。在iOS 10上,我正在使用MKPinAnnotationView,而在iOS 11上则使用MKMarkerAnnotationView

iOS 11会自动在地图缩放时隐藏和显示MKMarkerAnnotationViews。

enter image description here

这会带来一个不幸的副作用,即可能导致.selectAnnotation()无法可靠工作,因为标记在居中地图后仍然可能被隐藏。

我已经看过文档并理解其中的原因:

如果指定的注释未在屏幕上,并且因此没有关联的注释视图,则此方法无效。

有没有办法禁用注释聚合/隐藏?或者有没有一种方法来强制选择的注释可见?


这不是一个解决方案,但也许是一个解决方法的想法:在将地图居中后,尝试通过编程方式将地图缩放到更高的缩放状态(您可以尝试调整缩放因子,以使注释不重叠)。 - aksh1t
嗨@aksh1t,我考虑过这个问题,但我不想干扰用户选择的缩放级别。此外,我的一些注释可能非常接近,因此在某些情况下可能实际上并不起作用。 - Turnip
这很有道理。当我查看其他地图视图方法时,我得到了另一个想法:尝试使用你的注释调用showAnnotations:方法,然后执行selectAnnotation。(我不知道showAnnotation方法是否会改变缩放级别;它可能会改变缩放级别)。 - aksh1t
“showAnnotations” 不幸地会影响缩放。 - Turnip
1个回答

2
您可以将MKMarkerAnnotationViewdisplayPriority设置为1000的原始值,将不太有趣的MKMarkerAnnotationViewdisplayPriority设置为较低的值。这将导致该标记注释优先于其他注释。
在您的情况下,您可能希望保留对要选择的注释的引用,从地图视图中删除该注释并再次添加它。这将导致地图视图再次请求注释的视图,并且您可以调整优先级,使其高于周围的注释。例如:
    func showAnnotation()
    {
        self.specialAnnotation = annotations.last
        self.mapView.removeAnnotation(self.specialAnnotation)
        self.mapView.addAnnotation(self.specialAnnotation)
        self.mapView.setCenter(self.specialAnnotation.coordinate, animated: true)
        self.mapView.selectAnnotation(self.specialAnnotation, animated: true)
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
    {
        let markerView = mapView.dequeueReusableAnnotationView(withIdentifier: "Marker", for: annotation) as? MKMarkerAnnotationView
        let priority = (annotation as? Annotation) == self.specialAnnotation ? 1000 : 500
        markerView?.displayPriority = MKFeatureDisplayPriority(rawValue: priority)
        // optionally change the tint color for the selected annotation
        markerView?.markerTintColor = priority == 1000 ? .blue : .red
        return markerView
    }

其中specialAnnotation是符合MKAnnotation协议的对象。


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