【问题标题】:Swift, How to get information from a custom annotation on clickedSwift,如何在单击时从自定义注释中获取信息
【发布时间】:2016-05-19 10:27:20
【问题描述】:

我有以下自定义注释类:

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
    }
}

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

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 对象。目前我有这个方法,当我点击注释时会调用它,但我不确定如何从注释中检索特定对象。

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

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

谢谢。

【问题讨论】:

    标签: ios swift annotations mkmapview mkannotationview


    【解决方案1】:

    您可以在 didSelectAnnotationView 中获取您的 Annotation,然后它会为您提供 MKAnnotationView。这个 MKAnnotationView 将 MKAnnotation 作为一个对象。

    func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
        println("Annotation selected")
    
        if let annotation = view.annotation as? LocationMapAnnotation {
            println("Your annotation title: \(annotation.title)");
        }
    }
    

    【讨论】:

    • 是的!非常感谢它刚刚修复它!
    • 如果让 annotation = view.annotation as? LocationMapAnnotation 这是一个有效的比较吗?在注解(MKAnnotation)和“LocationMapAnnotation”(模型类 - Mappable)之间
    • @SyedUzairAhmed 这不是比较,而是在 swift 中进行类型转换的标准方法。 docs.swift.org/swift-book/LanguageGuide/TypeCasting.html
    猜你喜欢
    • 2014-12-07
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2010-12-20
    • 1970-01-01
    相关资源
    最近更新 更多