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

前端之家收集整理的这篇文章主要介绍了ios – 如何使用swift为多个注释设置数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
应该如何设置下面的数组.我试图在我的地图上添加多个注释.我能够在stackoverflow上找到下面的代码,但是他们没有展示如何设置数组.
  1. var objects = [
  2. //how should the array be setup here
  3. ]
  4.  
  5. for objecters in objects!{
  6. if let latit = objecters["Coordinates"]["Latitude"]{
  7. self.latitudepoint = latit as! String
  8. self.map.reloadInputViews()
  9. }
  10. else {
  11. continue
  12. }
  13. if let longi = objecters["Coordinates"]["Longitude"]{
  14. self.longitudepoint = longi as! String
  15. self.map.reloadInputViews()
  16. }
  17. else {
  18. continue
  19. }
  20. var annotation = MKPointAnnotation()
  21. var coord = CLLocationCoordinate2D(latitude: Double(self.latitudepoint)!,longitude: Double(self.longitudepoint)!)
  22. mapView.addAnnotation(annotation)
  23. }

解决方法

你可以做,例如:
  1. let locations = [
  2. ["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]
  3. ]
  4.  
  5. for location in locations {
  6. let annotation = MKPointAnnotation()
  7. annotation.title = location["title"] as? String
  8. annotation.coordinate = CLLocationCoordinate2D(latitude: location["latitude"] as! Double,longitude: location["longitude"] as! Double)
  9. mapView.addAnnotation(annotation)
  10. }

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

  1. struct Location {
  2. let title: String
  3. let latitude: Double
  4. let longitude: Double
  5. }
  6.  
  7. let locations = [
  8. Location(title: "New York,latitude: 40.713054,longitude: -74.007228),Location(title: "Los Angeles,latitude: 34.052238,longitude: -118.243344),Location(title: "Chicago,latitude: 41.883229,longitude: -87.632398)
  9. ]
  10.  
  11. for location in locations {
  12. let annotation = MKPointAnnotation()
  13. annotation.title = location.title
  14. annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude,longitude: location.longitude)
  15. mapView.addAnnotation(annotation)
  16. }

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

  1. let annotations = locations.map { location -> MKAnnotation in
  2. let annotation = MKPointAnnotation()
  3. annotation.title = location.title
  4. annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude,longitude: location.longitude)
  5. return annotation
  6. }
  7. mapView.addAnnotations(annotations)

猜你在找的iOS相关文章