【问题标题】:How to make MKMapView draggable with Image on top of it in SwiftUI如何在 SwiftUI 中使用 Image 使 MKMapView 可拖动
【发布时间】:2020-05-13 12:49:51
【问题描述】:

不久前,在故事板中,我添加了 MapView 并将禁用交互的 ImageView 放在它上面。我这样做是为了显示指向带有半径的地图中心的指针。 现在我想在 SwiftUI 中做同样的事情。所以我创建了 ZStack 并添加了 MKMapView 和 Image。显然 Image 后面的地图区域不可拖动。我试过.allowsHitTesting(false),但没有帮助。 点击可以正常工作并进入按钮。但是拖动没有到达 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)
            }
        }
    }
}

【问题讨论】:

    标签: ios swift mkmapview


    【解决方案1】:

    我找到了解决办法。将带有禁用交互的图像作为 UIView 添加为 MapView 的子视图。 示例:

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

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 2012-08-09
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      相关资源
      最近更新 更多