Swift手柄确实在同一位置的多个注释上进行选择

用户

选择相同位置的注释时,我试图调用一个函数。我的目标只是调用一个函数并显示两个餐厅的视图控制器,但是由于某些原因,当我在图像中选择标记时,下面的函数没有被调用。(它对于单个注释很好用)。谢谢你的帮助。

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    guard let anno = view.annotation as? MyAnno else { return }

    print(anno.post)
}

在此处输入图片说明

mmika1000

问题出在您的保卫声明中。正如我在简短的研究中可以发现的那样,iOS使用MKClusterAnnotation类型来放置相同位置的注释。因此,该view变量没有.annotation可确认您的自定义子类集合。

在这种情况下,您需要尝试将其强制转换为MKClusterAnnotation对象,而对象具有您想要.memberAnnotations的type属性[MKAnnotation]

我认为您的代码应该看起来像这样(虽然尚未测试):

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let anno = view.annotation as? MyAnno {
         print("Single Annotation selected:")        
         print(anno.post)

         // do anything
         return
    }

    if let anno = view.annotation as? MKClusterAnnotations {
        let selection: [MKAnnotation] = anno.memberAnnotations
        print("\(selection.count) Annotations selected:")

        // do something with your annotation group
        // you should now also be able to cast to your MyAnno class again 
        for item in selection {
            if let myAnno = item as? MyAnno {
                print(myAnno.post)
            }
        }
    }

}

有关更多信息,请参见使用MapKit注释聚类对地图进行整理

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章