MKMapView选择注释

时间:2015-03-18 20:30:12

标签: ios swift mkmapview

我是swift的新手,目前正试图弄清楚如何获取用户所选注释的数据。我有一个localsearch函数,它将添加注释,在用户选择一个我希望能够访问它之后。我尝试使用selectedAnnotations,但它似乎无法正常工作。

本地搜索:

func performSearch(){
    matchingItems.removeAll()
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = searchTextField.text
    request.region = mapView.region

    let search = MKLocalSearch(request: request)

    search.startWithCompletionHandler({(response:
        MKLocalSearchResponse!,
        error: NSError!) in

        if error != nil {
            println("Error occured in search: \(error.localizedDescription)")
        } else if response.mapItems.count == 0 {
            println("No matches found")
        } else {
            println("Matches found")

            for item in response.mapItems as [MKMapItem] {
                println("Name = \(item.name)")
                println("Phone = \(item.phoneNumber)")

                self.matchingItems.append(item as MKMapItem)
                println("Matching items = \(self.matchingItems.count)")

                var annotation = MKPointAnnotation()
                annotation.coordinate = item.placemark.coordinate
                annotation.title = item.name
                annotation.subtitle = item.placemark.title
                self.mapView.addAnnotation(annotation)

            }
        }
    })

从那里我试图使用

 var selectedAnnotations: [MKPointAnnotation]!
        // print signout location
        println(selectedAnnotations)

要访问注释,但这只是返回" nil"

注释方法:

    @IBAction func signoutToLocationButton(sender: AnyObject) {
    // saves current user location
    PFGeoPoint.geoPointForCurrentLocationInBackground {
        (geoPoint: PFGeoPoint!, error: NSError!) -> Void in
        if error == nil {
            // do something with the new geoPoint
            println(geoPoint)

            var signoutLocation = PFObject(className: "SignoutLocation")
            signoutLocation["Location"] = geoPoint
            signoutLocation.saveInBackgroundWithBlock {
                (success: Bool, error: NSError!)-> Void in
                if (success) {
                    // has been saved
                }
                else {
                    //went wrong
                }
            }

        }

        // get location of where they are signing out to
        self.mapView.selectedAnnotations(AnyObject)
        // print signout location
       //  println(selectedAnnotations)





    }

1 个答案:

答案 0 :(得分:1)

以下是如何使用selectedAnnotations属性的示例:

if self.mapView.selectedAnnotations?.count > 0 {

    if let ann = self.mapView.selectedAnnotations[0] as? MKAnnotation {

        println("selected annotation: \(ann.title!)")

        let c = ann.coordinate
        println("coordinate: \(c.latitude), \(c.longitude)")

        //do something else with ann...
    }
}

(尽管您是否需要或想要在// has been saved区块内而不是在室外执行此操作,这是您必须要弄清楚的。)