ios - 如何使用 swift 为多注释设置数组

标签 ios arrays swift mkannotation mkpointannotation

下面的数组应该怎么设置。我正在尝试在我的 map 上添加多个注释。我能够在 stackoverflow 上找到下面的代码,但它们没有显示如何设置数组。

var objects = [ 
                //how should the array be setup here 
              ]

for objecters in objects!{
    if let latit = objecters["Coordinates"]["Latitude"]{
        self.latitudepoint = latit as! String
        self.map.reloadInputViews()
    }
    else {
        continue
    }
    if let longi = objecters["Coordinates"]["Longitude"]{
        self.longitudepoint = longi as! String
        self.map.reloadInputViews()
    }
    else {
        continue
    }
    var annotation = MKPointAnnotation()
    var coord = CLLocationCoordinate2D(latitude: Double(self.latitudepoint)!,longitude: Double(self.longitudepoint)!)
    mapView.addAnnotation(annotation)
}

最佳答案

你可以这样做,例如:

let locations = [
    ["title": "New York, NY",    "latitude": 40.713054, "longitude": -74.007228],
    ["title": "Los Angeles, CA", "latitude": 34.052238, "longitude": -118.243344],
    ["title": "Chicago, IL",     "latitude": 41.883229, "longitude": -87.632398]
]

for location in locations {
    let annotation = MKPointAnnotation()
    annotation.title = location["title"] as? String
    annotation.coordinate = CLLocationCoordinate2D(latitude: location["latitude"] as! Double, longitude: location["longitude"] as! Double)
    mapView.addAnnotation(annotation)
}

或者,也可以使用自定义类型,例如:

struct Location {
    let title: String
    let latitude: Double
    let longitude: Double
}

let locations = [
    Location(title: "New York, NY",    latitude: 40.713054, longitude: -74.007228),
    Location(title: "Los Angeles, CA", latitude: 34.052238, longitude: -118.243344),
    Location(title: "Chicago, IL",     latitude: 41.883229, longitude: -87.632398)
]

for location in locations {
    let annotation = MKPointAnnotation()
    annotation.title = location.title
    annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
    mapView.addAnnotation(annotation)
}

或者您可以用 map 替换 for 循环:

let annotations = locations.map { location -> MKAnnotation in
    let annotation = MKPointAnnotation()
    annotation.title = location.title
    annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
    return annotation
}
mapView.addAnnotations(annotations)

关于ios - 如何使用 swift 为多注释设置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666968/

相关文章:

ruby-on-rails - 在 ruby​​ 中迭代数组并使用给定字符串搜索匹配元素

ios - 如何在应用程序处于后台时同步位置

Swift 组合布局 contentInsets.top 不适用于页眉

ios - UIView动画隐藏和显示

ios - iOS5上奇怪的UIButton行为

javascript - 从输入修改数组然后返回输出

swift - 协议(protocol)扩展中的嵌套初始化

ios - FQL 查询以查看用户是否喜欢某个帖子

objective-c - 在 UIWebView 中使用 tiff 和 gif 格式图像时出现问题

java - 将字节数组编码为十六进制字符串