T. Kearsley T. Kearsley - 1 year ago 123
Swift Question

MKAnnotationView Swift Adding "Info" button

I am very new to swift (coming from python) I am struggling with creating a MKAnnotationView. I followed a tutorial by ray wenderlich but the code appears to be outdated. The function call does not seem to work or produce the "i" intended to be in the annotation of the pin. Here is the code I am currently using:

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

I am running Xcode 8.1, any help will be greatly appreciated.

Answer Source

Am using Xcode 8.1 and Swift 3.0 . For Some reason Delegate methods are not firing until you set delegate in storyboard:

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
        else {
            pinView!.annotation = annotation

        return pinView

for button Action

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

I am attaching sample project for your issue

Map Sample Project Swift 3. 0 Xcode 8.1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download