Skip to content

Instantly share code, notes, and snippets.

@levochkaa
Created February 5, 2024 10:41
Show Gist options
  • Save levochkaa/c2c0f1dbbda7cc319170001f1a8c1d3b to your computer and use it in GitHub Desktop.
Save levochkaa/c2c0f1dbbda7cc319170001f1a8c1d3b to your computer and use it in GitHub Desktop.
touchesBegan/touchesEnded for Apple's MKMapView in SwiftUI
import SwiftUI
import MapKit
struct ContentView: View {
@State var region = MKCoordinateRegion()
@State var touching = false
var body: some View {
MapView(
region: $region,
onTouchesBegan: {
touching = true
},
onTouchesEnded: {
touching = false
}
)
.overlay {
Rectangle()
.fill(touching ? .red : .blue)
.frame(width: 20, height: 20)
}
}
}
struct MapView: UIViewRepresentable {
@Binding var region: MKCoordinateRegion
let onTouchesBegan: () -> Void
let onTouchesEnded: () -> Void
@State private var mapView = MKMapView()
func makeUIView(context: Context) -> MKMapView {
mapView.delegate = context.coordinator
mapView.region = region
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate {
let parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
parent.region = mapView.region
parent.onTouchesBegan()
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
parent.onTouchesEnded()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment