SwiftUI Button on top of a MKMapView does not get triggered

雨燕双飞 提交于 2021-01-05 11:32:43

问题


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")
            }
        }
    }
}

回答1:


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 !!
            }
        }
    }
}


来源:https://stackoverflow.com/questions/63840027/swiftui-button-on-top-of-a-mkmapview-does-not-get-triggered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!