Swift,如何从单击的自定义注释中获取信息 [英] Swift, How to get information from a custom annotation on clicked

查看:26
本文介绍了Swift,如何从单击的自定义注释中获取信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下自定义注释类:

I've got the following custom annotation class:

import UIKit
import MapKit

class LocationMapAnnotation: NSObject, MKAnnotation {
    var title: String?
    var coordinate: CLLocationCoordinate2D
    var location: Location

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

我正在将注释加载到这样的地图视图中:

I am loading the annotations into a map view like this:

for i in 0..<allLocations.count{
            //Add an annotation
            let l: Location = self.allLocations[i] as! Location
            let coordinates = CLLocationCoordinate2DMake(l.latitude as Double, l.longitude as Double)
            let annotation = LocationAnnotation(title: l.name, coordinate: coordinates, location: l)
            mapView.addAnnotation(annotation)
        }

而且我想从选定的注释中获取 Location 对象.目前我有这个方法,每当我点击注释时都会调用它,但我不确定如何从注释中检索特定对象.

And I am wanting to get the Location object from the selected annotation. Currently I have this method which is called when ever I tap an annotation, but I am unsure how to retrieve the specific object from the annotation.

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
    print("Annotation selected")

    //performSegueWithIdentifier("locationInfoSegue", sender: self)
}

谢谢.

推荐答案

你可以在 didSelectAnnotationView 中获取你的 Annotation,然后它会给你 MKAnnotationView.这个 MKAnnotationView 将 MKAnnotation 作为一个对象.

You can get your Annotation within didSelectAnnotationView, which will then give you MKAnnotationView. This MKAnnotationView has MKAnnotation as an object.

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
    println("Annotation selected")

    if let annotation = view.annotation as? LocationMapAnnotation {
        println("Your annotation title: \(annotation.title)");
    }
}

这篇关于Swift,如何从单击的自定义注释中获取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆