How do I make a clickable pin in SwiftUI’s new Map view?

As of XCode 12.3 this appears to be functioning with buttons. One key gotcha that I noticed though was that if you use offsets then it’s possible your buttons will be placed out of the tappable area of the annotation.

In order to counter that you can add additional padding to account for the offset and keep it within tappable bounds:

MapAnnotation(coordinate: item.placemark.coordinate) {
  ZStack {
      MapPinView() // My view for showing a precise pin
      VStack { // A prompt with interactive option, offset by 60pt
          Text("Use this location?")
          HStack {
              Button("Yes", action: {
                  print("yes")
              })
              
              Button("No", action: {
                  print("no")
              })
          }
      }
      .offset(x: 0, y: 60) // offset prompt so it's below the marker pin
  }
  .padding(.vertical, 60) // compensate for offset in tappable area of annotation. pad both the top AND the bottom to keep contents centered
}

Leave a Comment