2015-07-19 4 views
2

У меня есть mapView, заполненный маркерами с использованием MKAnnotations. Я могу получить массив аннотаций в порядке. Однако, как я могу определить индекс маркера, который используется? Скажем, я постучал маркером, и MKAnnotation появился. Как получить этот экземпляр аннотации?Как получить доступ к определенному индексу MKAnnotation

ViewDidAppear код:

for (var i=0; i<latArray.count; i++) { 

    let individualAnnotation = Annotations(title: addressArray[i], 
     coordinate: CLLocationCoordinate2D(latitude: latArray[i], longitude: longArray[i])) 

    mapView.addAnnotation(individualAnnotation) 
    }   
    //store annotations into a variable 
    var annotationArray = self.mapView.annotations 

    //prints out an current annotations in array 
    //Result: [<AppName.Annotations: 0x185535a0>, <AppName.Annotations: 0x1663a5c0>, <AppName.Annotations: 0x18575fa0>, <AppName.Annotations: 0x185533a0>, <AppName.Annotations: 0x18553800>] 
    println(annotationArray) 

аннотаций Класс: импорт MapKit

class Annotations: NSObject, MKAnnotation { 
    let title: String 
    //let locationName: String 
    //let discipline: String 
    let coordinate: CLLocationCoordinate2D 

    init(title: String, coordinate: CLLocationCoordinate2D) { 
     self.title = title 
     self.coordinate = coordinate 

    super.init() 
} 

var subtitle: String { 
    return title 
} 
} 

ответ

1

MKMapViewDelegate предоставляет метод делегата mapView:annotationView:calloutAccessoryControlTapped: Реализация этого метода обеспечивает вам MKAnnotationView экземпляра MKAnnotation вы ищете , Вы можете вызвать свойство M12nnotationView annotation, чтобы получить соответствующий экземпляр MKAnnotation.

import UIKit 
import MapKit 

class ViewController: UIViewController, MKMapViewDelegate { 

    @IBOutlet weak var mapView: MKMapView! 

    var sortedAnnotationArray: [MKAnnotation] = [] //create your array of annotations. 

    //your ViewDidAppear now looks like: 
    override func viewDidAppear(animated: Bool) { 
     super.viewDidAppear(animated) 
     for (var i = 0; i < latArray.count; i++) { 
     let individualAnnotation = Annotations(title: addressArray[i], coordinate: CLLocationCoordinate2D(latitude: latArray[i], longitude: longArray[i])) 
     mapView.addAnnotation(individualAnnotation) 
     //append the newly added annotation to the array 
     sortedAnnotationArray.append(individualAnnotation) 
     } 
    }  



    func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) { 
     let theAnnotation = view.annotation 
     for (index, value) in enumerate(sortedAnnotationArray) { 
      if value === theAnnotation { 
       println("The annotation's array index is \(index)") 
      } 
     } 
    } 
} 
+0

Спасибо, это было правильно. –

+0

Привет, Джадсон, этот метод работает, однако он не организован, когда был создан маркер. Кажется, случайным образом вытащить маркеры в массив. Вы знаете, как организовать индекс, когда он был создан? –

+1

массив mapView.annotations не сортируется к моменту добавления аннотации к представлению карты. Вы можете сохранить свой отсортированный массив аннотаций. Итак, вы начинаете с пустого массива, и каждый раз, когда вы вызываете mapView.addAnnotation(), также добавляйте эту аннотацию в конец вашего массива. Результатом будет массив аннотаций, отсортированный от самого раннего к последнему. Затем, вместо того, чтобы перебирать через mapView.annotations, как и выше, прокручивать отсортированный массив созданных аннотаций. –

Смежные вопросы