skip to content

A SwiftUI store-locator screen wraps MKMapView in a UIViewRepresentable with a region binding, and the map jitters and re-centres endlessly; what causes the loop and how do you fix it?

level: seniorimportance: should knowfreq 55%

answer

  1. two writers, one value
  2. update pushes, delegate pulls
  3. the echo comes back
  4. compare before you set
  5. never write state inside update

basics

~20 s

updateUIView sets the map's region from the binding, the map reports its slightly adjusted region through the delegate, the coordinator writes it back, and SwiftUI calls updateUIView again. Break the cycle by skipping values the map itself just reported.

solid answer

~40 s

The binding has two writers. Each SwiftUI update runs `updateUIView`, which calls `setRegion(_:animated:)`; the map adjusts the region to fit its aspect ratio and calls `mapView(_:regionDidChangeAnimated:)`; the coordinator writes that region into the binding; the parent re-renders and `updateUIView` runs again and calls `setRegion` with that value, which the map adjusts and reports once more, so the cycle never settles. The fix is to make each side ignore its own echo: the coordinator remembers the last region it saw or applied, `updateUIView` returns early when the binding matches it within a tolerance, and the delegate writes back only a region that differs from it. Also never write a binding synchronously inside `updateUIView`, because that modifies state during a view update.

code

swift · 45 lines
swift
import MapKit
import SwiftUI

struct StoreLocatorMap: UIViewRepresentable {
    @Binding var region: MKCoordinateRegion

    func makeCoordinator() -> Coordinator { Coordinator(region: $region) }

    func makeUIView(context: Context) -> MKMapView {
        let map = MKMapView()
        map.delegate = context.coordinator
        return map
    }

    func updateUIView(_ map: MKMapView, context: Context) {
        let coordinator = context.coordinator
        coordinator.region = $region
        // Skip the echo of a value the map itself just reported.
        if let last = coordinator.lastKnownRegion, last.isClose(to: region) { return }
        coordinator.lastKnownRegion = region
        map.setRegion(region, animated: true)
    }

    final class Coordinator: NSObject, MKMapViewDelegate {
        var region: Binding<MKCoordinateRegion>
        var lastKnownRegion: MKCoordinateRegion?
        init(region: Binding<MKCoordinateRegion>) { self.region = region }

        func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
            let current = mapView.region
            if let last = lastKnownRegion, last.isClose(to: current) { return }
            lastKnownRegion = current
            region.wrappedValue = current
        }
    }
}

extension MKCoordinateRegion {
    func isClose(to other: MKCoordinateRegion, tolerance: Double = 0.0001) -> Bool {
        abs(center.latitude - other.center.latitude) < tolerance
            && abs(center.longitude - other.center.longitude) < tolerance
            && abs(span.latitudeDelta - other.span.latitudeDelta) < tolerance
            && abs(span.longitudeDelta - other.span.longitudeDelta) < tolerance
    }
}

go deeper

for a junior

Recall that updateUIView runs on every relevant SwiftUI change, so any code there must be safe to repeat.

for a middle

Explain the two data directions across a representable: state in through updateUIView, user changes out through a coordinator writing a binding.

for a senior

Trace the cycle step by step and fix it with echo suppression in the coordinator, a tolerance, and no synchronous state writes during an update.

for a principal

Make two-way representables a reviewed pattern: one owner per value, a documented echo guard, and tests that drive both directions.

## The setup A SwiftUI store-locator screen owns the map's region in `@State` and passes it down as a binding, so other controls can move the map ("Centre on my store") and the screen can read where the user has panned. The map itself is UIKit: an `MKMapView` wrapped in a `UIViewRepresentable` with `@Binding var region: MKCoordinateRegion`. A `Coordinator` is the map's delegate. The naive version looks reasonable: - `updateUIView(_:context:)` calls `map.setRegion(region, animated: true)`; - `mapView(_:regionDidChangeAnimated:)` in the coordinator writes `mapView.region` back into the binding. On device the map jitters, re-centres after every pan, or never settles. ## Tracing the loop The binding now has **two writers**, and each one reacts to the other's writes: 1. SwiftUI runs `updateUIView`, which calls `setRegion(_:animated:)` with the binding's value. 2. `MKMapView` does **not** keep that exact region. It adjusts the span to fit its own aspect ratio, so its `region` ends up slightly different from the value it was given. 3. When the change finishes, the delegate method fires and the coordinator writes the adjusted region into the binding. 4. The parent's state changed, so SwiftUI re-renders the parent and calls `updateUIView` again. 5. `updateUIView` calls `setRegion` again with a value the map adjusts once more, and the cycle restarts at step 2. The same cycle can start from the user's side: a pan ends, the delegate writes the binding, SwiftUI calls `updateUIView`, and the map is told to animate to a region it is already showing. ## The fix: ignore your own echo Each side must recognise a value that merely came back from the other side. 1. **Remember the last region either side produced** in the coordinator (`lastKnownRegion`). 2. **In `updateUIView`**, return early when the binding's region matches it **within a tolerance**; otherwise record it and call `setRegion`. 3. **In the delegate**, return early when the map's region matches it; otherwise record it and write the binding. 4. **Refresh the binding** the coordinator writes to, `context.coordinator.region = $region`, at the top of `updateUIView`, because the coordinator is created once while the representable struct is rebuilt on every update. With this in place each real change crosses the boundary once and stops: | Change starts in | Crosses to | Comes back as | Result | |---|---|---|---| | SwiftUI (button sets the region) | The map, through `setRegion` | The map's adjusted region, written once | `updateUIView` sees it matches and stops | | UIKit (user pans) | SwiftUI, through the binding | A call to `updateUIView` | It matches the recorded value and stops | Why a **tolerance**: the map's adjustment and floating-point coordinates mean exact equality would treat the echo as new. `MKCoordinateRegion` is a C struct without `Equatable`, so you compare the centre and span fields yourself. ## The rule underneath: no state writes during an update A related mistake is to "keep things in sync" by writing the binding inside `updateUIView`. That changes SwiftUI state **while a view update is in progress**, which SwiftUI treats as undefined behaviour and warns about at run time, and it can schedule yet another update. The same applies to a delegate callback that UIKit happens to deliver **synchronously** from inside `setRegion` while `updateUIView` is still running. Options: - guard such writes with the echo check, so the callback does nothing during your own update; - or defer the write with `Task { @MainActor in ... }` so it lands after the update finishes. ## What does not fix it - **Setting the region only in `makeUIView`.** The loop stops because SwiftUI can no longer move the map; the binding has become one-way. - **Turning off animation.** It changes when the delegate fires, not whether the adjusted value bounces back. - **Replacing the binding with a constant.** The parent then never learns where the user moved the map. ## The general pattern This is not specific to maps. Any representable with a two-way value, such as a text view's text, a scroll position, a slider's value or a page index, has the same shape: - state flows **in** through `updateUIView`; - user changes flow **out** through the coordinator; - one of them must recognise the other's echo. A good review checklist for such wrappers: every `set` in `updateUIView` is guarded by a comparison, every write-back in the coordinator is guarded by the same comparison, and no binding is written synchronously during an update.

  • Why compare regions with a tolerance instead of exact equality?
    The map does not keep the region you pass: it adjusts the span to fit its own aspect ratio, and coordinates come back as floating-point values. Exact equality would treat the adjusted echo as a new value and push it again, which restarts the loop you are trying to stop.
  • The coordinator stores the binding it got in makeCoordinator(); why reassign it in updateUIView?
    The coordinator is created once, while SwiftUI rebuilds the representable on every parent update and may hand it a binding to different storage, for example when the parent swaps which store's region it shows. Reassigning `context.coordinator.region = $region` keeps write-backs going to the binding the current struct carries.
  • What should you do when a delegate callback can fire synchronously while updateUIView is still running?
    Do not write SwiftUI state from it at that moment: a state change during a view update is undefined behaviour and SwiftUI warns about it at run time. Guard the write with the echo check, or move it out of the update with `Task { @MainActor in ... }` so the binding changes after the update finishes.

Two people holding one thermostat who each nudge it to what they just read off the other: unless one of them recognises their own last setting, they keep adjusting forever.

  • Calling setRegion unconditionally in updateUIView on every SwiftUI update.
  • Comparing map regions with exact equality to detect a change.
  • Writing the binding directly inside updateUIView to keep both sides in sync.
  • Fixing the jitter by moving the region into makeUIView only, so later changes never apply.
  • Assuming the map keeps exactly the region it was given.