前段时间,我在storyboard中添加了MapView,并在上面放置了ImageView,禁用了交互。现在我想在SwiftUI中做同样的事情。所以我创建了ZStack并添加了MKMapView和Image。很明显,Image后面的地图区域是不能拖动的。我尝试了 .allowsHitTesting(false)
但它没有任何帮助.Tap工作正常,并下降到按钮。但是拖拽却不能到达MapView。
我试过用MapViewOverlay和替换覆盖每次地图移动的解决方案,它作为解决方案有点好。但还是想找出我在地图和图像的解决方案中缺少什么。
这是我的示例代码。
struct EditDestinationView: View {
var body: some View {
VStack {
Text("Edit Destination")
ZStack {
Button("Tap Me") {
print("Button was tapped")
}
.frame(width: 100, height: 100)
.background(Color.white)
DestinationMapView(centerCoordinate: .constant(
CLLocationCoordinate2D()
)
)
.allowsHitTesting(false)
Rectangle()
.fill(Color.red.opacity(0.2))
.frame(width: 300, height: 300)
.clipShape(Circle())
.allowsHitTesting(false)
}
}
}
}
我找到了一个解决方案。将图像作为UIView添加到MapView.Example的子视图中,并禁用交互。
class Coordinator: NSObject, MKMapViewDelegate {
var parent: DestinationMapView
var circleAdded: Bool = false
func mapViewWillStartRenderingMap(_ mapView: MKMapView) {
addCircle(mapView)
}
func addCircle(_ uiView: MKMapView) {
if circleAdded == false && uiView.frame.size.height > 0 {
let image = UIImageView(image: UIImage(named: "radius"))
image.isUserInteractionEnabled = false
image.center = CGPoint(x: uiView.frame.size.width/2, y: uiView.frame.size.height/2)
uiView.addSubview(image)
circleAdded = true
}
}
}