Search code examples
iosswiftmkmapviewmkannotationview

How to have a MKPinAnnotationView open when pin is dropped


I currently am dropping a reusable pin using this function:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{

    guard !(annotation is MKUserLocation) else { return nil }
    let reuseId = "pin"
    var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
    }
    pinView?.pinTintColor = UIColor.orange
    pinView?.canShowCallout = true

    let smallSquare = CGSize(width: 30, height: 30)
    let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare))
    button.setTitle("Test", for: UIControlState())
    button.addTarget(self, action: #selector(triggerConfirmedLocation), for: .touchUpInside)

    pinView?.leftCalloutAccessoryView = button
    pinView?.rightCalloutAccessoryView = button
    return pinView
}

Currently the user has to tap on the pin to see the annotation; however, I need the annotation to be open when the pin is dropped.

I have tried these methods:

pinView?.isSelected = true

and

mapView.selectedAnnotations(reuse, animated: true)

However the first method does nothing.

The second method has an error of "Cannot call value of non-function type '[MKAnnotation]'"


Solution

  • You need this method from MKMapView using:

    func selectAnnotation(_ annotation: MKAnnotation, animated: Bool)
    

    You can pass the annotation from the delegate override like so:

    mapView.selectAnnotation(annotation, animated: true)
    

    Just call that before returning the pinView and you'll be good to go.

    Hope that helps.