2015-07-19 88 views
2

我有一個使用MKAnnotations標記填充的mapView。我能夠很好地獲得註釋數組。但是,如何找出被點擊的標記的索引?假設我點擊了一個標記並彈出了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:實現此方法爲您提供與您正在尋找的MKAnnotation實例的MKAnnotationView 。您可以調用MKAnnotationView的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循環,循環遍歷已創建的已排序的批註數組。 –

相關問題