MKMapView顶部的SwiftUI按钮未被触发

zqdjd7g9  于 2023-04-04  发布在  Swift
关注(0)|答案(2)|浏览(139)

我在MKMapView上面有一个按钮。但是当点击按钮时,按钮不会被触发。你知道缺少什么吗?
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")
            }
        }
    }
}
wbrvyc0a

wbrvyc0a1#

给予它更多的内部空间,以更好地识别。这里是修复和测试的变体(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 !!
            }
        }
    }
}
of1yzvn4

of1yzvn42#

我想提一些稍微不同但可能对寻找答案并到达此页面的人有用的东西。
如果你的按钮(特别是在ScrollView中)在SwiftUI的Map之上,那么按钮的点击区域可能没有它应该的那么大。我解决这个问题的方法是在ScrollView中添加一个空的.onTapGesture { }
示例:

var body: some View {
    ZStack {
        // A Map causes an issue with buttons' tap areas
        Map(mapRect: .constant(.world))

        ScrollView([.horizontal]) {
            HStack {
                ForEach(["M", "N"]) { letter in
                    Button(letter) { }
                }
            }
        }
        .onTapGesture { } // <-- !!! Needed to avoid issue with buttons !!!
    }
}

相关问题