我通过 UIViewRepresentable 呈现一个 map View ,并希望在 map 中心有一个图像“目标”。该图像会阻止在图像上启动的点击事件和平移手势。因此,将注释拖放到图像下方的 map 上意味着无法启动其标注。
我读过有关透明度问题的信息,因此我将目标图像的“清晰”区域重新制作为白色,不透明度为 1%,但行为没有变化。
将 allowsHitTesting
设置为 false 也不起作用,尽管如果我在图像下方插入一个按钮(代码中的测试 1),我可以点击它,但不能点击 map /注释,所以似乎有MapKit 元素和我自己添加的 SwiftUI View 之间的区别。
import SwiftUI
import MapKit
struct ContentView: View {
var body: some View {
ZStack {
MapView()
/*Test 1*/ Button("Tap Me") {
print("Text button was tapped")
}
Image("target")
.frame(width: 90, height: 90)
.allowsHitTesting(false)
/*Test 2*/ Rectangle()
.fill(Color.red.opacity(0.2))
.frame(width: 90, height: 90)
.allowsHitTesting(false)
/*Test 3*/ Button(action: {print("Round button was tapped")}) {
Circle()
.fill(Color.red.opacity(0.2))
.frame(width: 90, height: 90)
}
.allowsHitTesting(false)
.disabled(true)
}
}
}
struct MapView: UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
map.mapType = .standard
map.isRotateEnabled = false
let location = CLLocation(latitude: 40.763783, longitude: -73.973133)
let region = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: 2000, longitudinalMeters: 2000)
map.setRegion(region, animated: true)
let annotation = MyAnnotation(coordinate: location.coordinate)
annotation.title = "Title"
annotation.subtitle = "Subtitle"
map.addAnnotation(annotation)
return map
}
func updateUIView(_ uiView: MKMapView, context: Context) {
}
}
class MyAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
}
}
将图像交换为矩形(代码中的测试 2)具有相同的行为,我可以与添加的 View 进行交互,但无法将触摸/平移传递给 MapKit 元素。我什至尝试使用禁用按钮,希望其 HitTest 更符合我想要实现的目标。遗憾的是没有。
有谁知道通过另一个 View 与 map View (点击和平移)进行交互的方法吗?
最佳答案
是的,到目前为止,即使是透明图像也不允许穿透。在您的情况下,足够简单,可能的方法是创建自定义形状,如下所示。形状确实可以传递命中。
这是显示方向的简单形状演示。
struct Cross: Shape {
func path(in rect: CGRect) -> Path {
return Path { path in
path.move(to: CGPoint(x: rect.midX, y: 0))
path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
path.move(to: CGPoint(x: 0, y: rect.midY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
path.move(to: CGPoint(x: rect.midX, y: rect.midY))
path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: 10, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 360), clockwise: false)
}
}
}
struct ContentView: View {
var body: some View {
ZStack {
MapView()
Cross().stroke(Color.red)
.frame(width: 90, height: 90)
}
}
}
关于SwiftUI View 阻止对 MapKit 的触摸,但不会阻止其他 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61303270/