【问题标题】:Get annotation pin tap event MapKit Swift获取注解 pin tap 事件 MapKit Swift
【发布时间】:2017-03-06 19:44:10
【问题描述】:

我有一个类的数组。并在 mkmapview 中添加一些注释引脚。

var events = [Events]()

   for event in events {
        let eventpins = MKPointAnnotation()
        eventpins.title = event.eventName
        eventpins.coordinate = CLLocationCoordinate2D(latitude: event.eventLat, longitude: event.eventLon)
        mapView.addAnnotation(eventpins)
    }

使用 map 的委托,我已经实现了一个功能

 func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print(view.annotation?.title! ?? "")
}

如何获取数组events 的哪一行被窃听? 因为我想在另一个 ViewController 中继续,我想发送这个类对象。

【问题讨论】:

    标签: ios swift swift3 mkmapview mkannotation


    【解决方案1】:

    您应该创建一个自定义注释类,例如:

    class EventAnnotation : MKPointAnnotation {
        var myEvent:Event?
    }
    

    然后,当您添加注释时,您会将 Event 与自定义注释链接:

    for event in events {
        let eventpins = EventAnnotation()
        eventpins.myEvent = event // Here we link the event with the annotation
        eventpins.title = event.eventName
        eventpins.coordinate = CLLocationCoordinate2D(latitude: event.eventLat, longitude: event.eventLon)
        mapView.addAnnotation(eventpins)
    }
    

    现在,您可以在委托函数中访问事件:

    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        // first ensure that it really is an EventAnnotation:
        if let eventAnnotation = view.annotation as? EventAnnotation {
            let theEvent = eventAnnotation.myEvent
            // now do somthing with your event
        }
    }
    

    【讨论】:

    • 正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多