【问题标题】:Convert MKAnnotation array to set将 MKAnnotation 数组转换为设置
【发布时间】:2018-08-18 11:13:06
【问题描述】:

我有一种情况,我在 swift 中将地图注释作为 [MKAnnotation] 数组。现在我需要将其转换为一组以进行某些操作。我怎样才能快速做到这一点?基本上我需要在更新地图视图时只在地图上添加不存在的注释。

【问题讨论】:

  • 这给了我一个错误:“无法推断通用参数'元素'”
  • 你的数组是如何声明的?
  • 它基本上是一个地图视图。所以我正在服用 self.mapView.annotations
  • 因为这将是一个NSArray,你需要告诉 swift 你的具体元素类型; let annotationSet = Set<MKAnnotation>(annotationArray),但实际上您应该拥有自己的特定注释对象数组,而不是依赖于地图视图 annotations 属性
  • 我尝试了上述方法,但这给了我一个错误:“类型'MKAnnotation'不符合协议'Hashable'”

标签: ios swift mapkit


【解决方案1】:

你可以通过mapView.view(for:)as mentioned here查看地图上是否存在注解:

    if (self.mapView.view(for: annotation) != nil) {
        print("pin already on mapview")
    }

【讨论】:

    【解决方案2】:

    “基本上我只需要在地图上添加不存在的注释,同时更新地图视图。”

    我们首先需要定义什么使两个注释相等(在您的场景中)。一旦清楚,您将覆盖 isEqual 方法。然后,您可以将注释添加到 Set

    这是一个例子:

    class MyAnnotation : NSObject,MKAnnotation{
        var coordinate: CLLocationCoordinate2D
        var title: String?
    
        convenience init(coord : CLLocationCoordinate2D, title: String) {
            self.init()
            self.coordinate = coord
            self.title = title
        }
    
        private override init() {
            self.coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
        }
    
        override func isEqual(_ object: Any?) -> Bool {
            if let annot = object as? MyAnnotation{
                // Add your defintion of equality here. i.e what determines if two Annotations are equal.
                return annot.coordinate.latitude == coordinate.latitude && annot.coordinate.longitude == coordinate.longitude && annot.title == title
            }
            return false
        }
    }
    

    在上面的代码中,如果MyAnnotation 的两个实例具有相同的坐标和相同的标题,则它们被认为是相等的。

    let ann1 = MyAnnotation(coord: CLLocationCoordinate2D(latitude: 20.0, longitude: 30.0), title: "Annot A")
    let ann2 = MyAnnotation(coord: CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0), title: "Annot B")
    let ann3 = MyAnnotation(coord: CLLocationCoordinate2D(latitude: 20.0, longitude: 30.0), title: "Annot A")
    
    var annSet = Set<MyAnnotation>()
    annSet.insert(ann1)
    annSet.insert(ann2)
    annSet.insert(ann3)
    
    print(annSet.count)  // Output : 2 (ann1 & ann3 are equal)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多