MKAnnotationView Swift添加"信息"按键

时间:2016-11-08 02:47:25

标签: ios swift mapkit

我是swift的新手(来自python)我正在努力创建一个MKAnnotationView。我遵循了ray wenderlich的教程,但代码似乎已经过时了。函数调用似乎不起作用或产生" i"打算在引脚的注释中。这是我目前使用的代码:

import MapKit

extension ViewController: MKMapViewDelegate {

// 1
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    if let annotation = annotation as? Artwork {
        let identifier = "pin"
        var view: MKPinAnnotationView
        if let dequeuedView = MapView.dequeueReusableAnnotationView(withIdentifier: identifier)
            as? MKPinAnnotationView { // 2
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            // 3
            view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            view.canShowCallout = true
            view.calloutOffset = CGPoint(x: -5, y: 5)
            let button = UIButton(type:.detailDisclosure)
            view.rightCalloutAccessoryView = button as UIView
        }
        return view
    }
    return nil
    }
}

我正在运行Xcode 8.1,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

使用Xcode 8.1和Swift 3.0。出于某种原因,在故事板中设置委托之前,不会触发委托方法:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
    {
        if annotation is MKUserLocation {return nil}

        let reuseId = "pin"

        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
        if pinView == nil {
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            pinView!.canShowCallout = true
            pinView!.animatesDrop = true
            let calloutButton = UIButton(type: .DetailDisclosure)
            pinView!.rightCalloutAccessoryView = calloutButton
            pinView!.sizeToFit()
        }
        else {
            pinView!.annotation = annotation
        }


        return pinView
    }

按钮动作

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        if control == view.rightCalloutAccessoryView {
          print("button tapped")
        }
    }

我正在为你的问题附上示例项目

https://jsfiddle.net/7nttub0b/3/