Spot the bug
The map stutters and keeps snapping back while the user drags. Tap the line that causes it.
struct MapView: UIViewRepresentable {@Binding var center: CLLocationCoordinate2Dfunc makeUIView(context: Context) -> MKMapView {let map = MKMapView()map.delegate = context.coordinatorreturn map}func updateUIView(_ map: MKMapView, context: Context) {map.setCenter(center, animated: true)}func makeCoordinator() -> Coordinator { Coordinator(self) }final class Coordinator: NSObject, MKMapViewDelegate {var parent: MapViewinit(_ parent: MapView) { self.parent = parent }func mapViewDidChangeVisibleRegion(_ map: MKMapView) {parent.center = map.centerCoordinate}}}
Hint 1 of 2
What does every SwiftUI update do to the map?
Hint 2 of 2
What happens after the delegate writes the binding?
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 9
map.setCenter(center, animated: true)
Line 9 re-centres the map on every update. Dragging writes the binding (line 16), which triggers an update, which re-centres the map, and so on. Only call setCenter when the new centre is meaningfully different from the map's current one.