我正在尝试向ContentView.swift中的Mapkit地图视图添加手势(轻击,轻扫等),但无济于事。我从googlemaps开始,然后尝试了Mapkit。我知道有两种向视图添加手势的方法。
import SwiftUI
struct ContentView: View {
var body: some View {
MapView()
.onTapGesture(count: 2) {
print("Double tapped!")
}
.edgesIgnoringSafeArea(.all)
}
struct MapView: UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
let tap = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.doubleTapped))
tap.numberOfTapsRequired = 2
mapView.addGestureRecognizer(tap)
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
@objc func doubleTapped() {
print("Double Tapped...")
}
}
}
这些方法似乎都不起作用。对我来说,更可取的方法是#1,但是我尝试了像#2一样的替代方法。关于我在做什么错的任何想法吗?我正在使用Xcode 11.4(11E146)。谢谢!
以下内容对我有用...
使用以下扩展名定义MapView:
import SwiftUI
import Foundation
import MapKit
struct MapView {
var coordinate: CLLocationCoordinate2D
func makeMapView() -> MKMapView {
MKMapView(frame: .zero)
}
func updateMapView(_ view: MKMapView, context: Context) {
let span = MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)
let region = MKCoordinateRegion(center: coordinate, span: span)
view.setRegion(region, animated: true)
}
}
extension MapView: NSViewRepresentable {
func makeNSView(context: Context) -> MKMapView {
makeMapView()
}
func updateNSView(_ nsView: MKMapView, context: Context) {
updateMapView(nsView, context: context)
dropPin(nsView)
}
}
然后在SwiftUI视图中使用它时,将具有所有可用的标准手势。
MapView(coordinate: location)
.onTapGesture(count: 2) {
print("Double tapped!")
}
.onLongPressGesture {
print("Long pressed")
}
希望这会帮助👍