swiftioswiftuimkmapviewzstack

SwiftUI Button on top of a MKMapView does not get triggered


I have a button on top of a MKMapView. But the button does not get triggered when it's tapped on. Do you know what's missing?

MapView.swift

import SwiftUI
import UIKit
import MapKit

struct MapView: UIViewRepresentable {

    func makeUIView(context: Context) -> MKMapView {
        let mkMapView = MKMapView()
        return mkMapView
    }
    
    func updateUIView(_ uiView: MKMapView, context: Context) { }
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    class Coordinator: NSObject, MKMapViewDelegate { }
}

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            MapView()
            Button(action: {
                print("Tapped")
            }) {
                Image(systemName: "lock.fill")
            }
        }
    }
}

Solution

  • Give it just a bit more internal space to be better recognizable. Here is fixed & tested variant (Xcode 12 / iOS 14):

    struct TestButtonWithMap: View {
        @State private var locked = true
        var body: some View {
            ZStack {
                MapView()
                Button(action: {
                    print("Tapped")
                    self.locked.toggle()
                }) {
                    Image(systemName: locked ? "lock.fill" : "lock.open")
                        .padding()      // << here !!
                }
            }
        }
    }