【问题标题】:How do I remove all map annotations in swift 2如何在 swift 2 中删除所有地图注释
【发布时间】:2015-09-29 17:21:44
【问题描述】:

我有工作代码可以使用按钮删除所有地图注释,但在我更新到 xcode 7 后,我遇到了错误:

类型“MKAnnotation”不符合协议“SequenceType”

if let annotations = (self.mapView.annotations as? MKAnnotation){
    for _annotation in annotations {
        if let annotation = _annotation as? MKAnnotation {
            self.mapView.removeAnnotation(annotation)
        }
    }
}

【问题讨论】:

    标签: xcode swift mapkit swift2


    【解决方案1】:

    在 Swift 2 中,annotations 被声明为非可选数组 [MKAnnotation],因此您可以轻松编写

    let allAnnotations = self.mapView.annotations
    self.mapView.removeAnnotations(allAnnotations)
    

    没有任何类型转换。

    【讨论】:

      【解决方案2】:
      self.mapView.removeAnnotations(self.mapView.annotations)
      

      如果您不想删除用户位置。

      self.mapView.annotations.forEach {
        if !($0 is MKUserLocation) {
          self.mapView.removeAnnotation($0)
        }
      }
      

      注意:Objective-C 现在有泛型,不再需要强制转换 'annotations' 数组的元素。

      【讨论】:

      • 我想使用你的代码,但它说:意外发现 nil while...我知道这是什么意思,但我不知道哪个值是 nil。
      【解决方案3】:

      SWIFT 5

      如果您不想删除用户位置标记:

      let annotations = mapView.annotations.filter({ !($0 is MKUserLocation) })
      mapView.removeAnnotations(annotations)
      

      【讨论】:

        【解决方案4】:

        问题在于有两种方法。一个是 removeAnnotation,它接受一个 MKAnnotation 对象,另一个是 removeAnnotations,它接受一个 MKAnnotations 数组,注意一个末尾的“s”而不是另一个。尝试从[MKAnnotation] 转换为MKAnnotation 单个对象的数组或反之亦然将使程序崩溃。这行代码 self.mapView.annotations 创建了一个数组。因此,如果您使用方法 removeAnnotation,则需要为数组中的单个对象索引数组,如下所示:

        let previousAnnotations = self.mapView.annotations
        if !previousAnnotations.isEmpty{
          self.mapView.removeAnnotation(previousAnnotations[0])
        }
        

        因此,您可以在保留用户位置的同时删除各种注释。在尝试从中删除对象之前,您应该始终测试您的数组,否则可能会出现越界或 nil 错误。

        注意:使用 removeAnnotations 方法(带有 s)删除所有注释。 如果你得到一个零,这意味着你有一个空数组。您可以通过在 if 之后添加 else 语句来验证这一点,如下所示;

            else{print("empty array")}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-29
          • 2011-03-02
          • 1970-01-01
          • 2014-05-16
          • 1970-01-01
          相关资源
          最近更新 更多