skip to content

In SwiftUI, when do a UIViewRepresentable's makeUIView, updateUIView and dismantleUIView run, and how does a Coordinator act as the UIKit view's delegate?

level: middleimportance: must knowfreq 74%

answer

  1. create once, update many
  2. the struct is rebuilt, the view is not
  3. coordinator made before the view
  4. delegate callbacks need an object
  5. refresh the coordinator's copy

basics

~20 s

makeUIView creates the UIKit view once per identity, updateUIView pushes current SwiftUI state into it whenever that state changes, and the static dismantleUIView cleans up on removal. A Coordinator, created first, is the long-lived object that serves as delegate.

solid answer

~40 s

A `UIViewRepresentable` is a short-lived struct that SwiftUI recreates on every parent `body` pass, while the `UIView` it manages lives as long as the representable keeps its identity. SwiftUI calls `makeCoordinator()` first, then `makeUIView(context:)` once to create and configure the view, then `updateUIView(_:context:)` whenever inputs it depends on change, applying current state to the existing view. `static func dismantleUIView(_:coordinator:)` runs when the view leaves the hierarchy; it is optional. Delegates and target-action need a reference-type object that outlives each struct, which is the `Coordinator`: you assign `context.coordinator` as delegate in `makeUIView`, and in `updateUIView` you refresh whatever copy of the representable the coordinator keeps, so its closures are current.

code

swift · 34 lines
swift
import MapKit
import SwiftUI

struct StoreMap: UIViewRepresentable {
    var stores: [MKPointAnnotation]
    var onSelect: (MKPointAnnotation) -> Void

    func makeCoordinator() -> Coordinator { Coordinator(parent: self) }

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

    func updateUIView(_ map: MKMapView, context: Context) {
        context.coordinator.parent = self
        map.removeAnnotations(map.annotations)
        map.addAnnotations(stores)
    }

    static func dismantleUIView(_ map: MKMapView, coordinator: Coordinator) {
        map.delegate = nil
    }

    final class Coordinator: NSObject, MKMapViewDelegate {
        var parent: StoreMap
        init(parent: StoreMap) { self.parent = parent }

        func mapView(_ mapView: MKMapView, didSelect annotation: any MKAnnotation) {
            if let store = annotation as? MKPointAnnotation { parent.onSelect(store) }
        }
    }
}

go deeper

for a junior

Recall the three methods and their order of use: make once, update repeatedly, dismantle at removal, plus makeCoordinator before make.

for a middle

Explain why the coordinator exists: delegates need a stable reference type, and the representable struct is rebuilt on every update.

for a senior

Show the staleness trap of a coordinator holding the first struct copy, and keep updateUIView cheap and idempotent because it runs often.

for a principal

Set a team pattern for wrappers: configuration in make, all state in update, the coordinator as the only delegate, cleanup in dismantle.

## What a representable is `UIViewRepresentable` (iOS 13) is a SwiftUI protocol for placing a **UIKit view** inside a SwiftUI hierarchy. A type that adopts it is itself a SwiftUI `View` whose `Body` is `Never`: instead of a `body`, it provides methods SwiftUI calls to create, update and tear down a real `UIView`. `UIViewControllerRepresentable` is the same contract for a `UIViewController`, with `makeUIViewController(context:)`, `updateUIViewController(_:context:)` and `dismantleUIViewController(_:coordinator:)`. The key to the whole lifecycle is a mismatch in lifetimes: - The **representable struct** is a cheap value. SwiftUI creates a new one every time the parent's `body` runs. - The **UIKit view** is an expensive, stateful object. SwiftUI keeps the same instance for as long as the representable keeps its **identity** in the hierarchy. ## The requirements and when they run | Requirement | Runs | Job | |---|---|---| | `makeCoordinator()` | Once per identity, before the view is made | Create the long-lived helper object (defaults to `Void`) | | `makeUIView(context:)` | Once per identity | Create the view and do one-time setup, such as setting its delegate | | `updateUIView(_:context:)` | After creation, then whenever inputs change | Apply the current SwiftUI state to the existing view | | `static dismantleUIView(_:coordinator:)` | When the view leaves the hierarchy | Clean up: detach delegates, stop timers or observers | | `sizeThatFits(_:uiView:context:)` | During layout (iOS 16 and later) | Optionally answer SwiftUI's size proposal | A few details from the declarations matter in interviews: 1. **The coordinator exists before the view.** The `Context` passed to `makeUIView(context:)` carries `context.coordinator`, so SwiftUI has already called `makeCoordinator()` by then. 2. **`Coordinator` defaults to `Void`.** When you need no helper, you implement nothing; the protocol supplies `makeCoordinator()` for that case. 3. **`dismantleUIView` is `static`** and has a default implementation. It receives the view and the coordinator, not `self`, so it cannot read the representable's current properties. 4. **`updateUIView` runs often.** SwiftUI calls it for changes affecting the view, so the code must be safe to repeat and cheap. ## Why a Coordinator, and how it acts as a delegate Apple's documentation is direct: the system **does not automatically communicate changes occurring within your view** to the rest of your SwiftUI interface; you provide a `Coordinator` to forward **target-action and delegate messages**. The reasons the struct cannot do this itself: - UIKit delegate protocols such as `MKMapViewDelegate` or `UITextFieldDelegate` are **class-bound**, so a struct cannot conform. - Even if it could, the struct is recreated on every update, while UIKit views such as `MKMapView` hold their delegate weakly and expect one stable object that something else keeps alive. So the pattern is: 1. Declare a nested `final class Coordinator: NSObject, MKMapViewDelegate`. 2. Return it from `makeCoordinator()`, usually passing `self` in so it can reach the representable's bindings and closures. 3. In `makeUIView`, set `map.delegate = context.coordinator`. 4. In delegate methods, forward to SwiftUI through a binding or a closure, for example `parent.onSelect(store)` when the user taps a store pin. ## The staleness trap Because the coordinator is created once, a coordinator that stores the representable from `makeCoordinator()` keeps the **first** copy. If the parent later passes a different `onSelect` closure or other new values, the coordinator would still call the old ones. The fix is one line at the top of `updateUIView`: ```swift context.coordinator.parent = self ``` ## Using the context `UIViewRepresentableContext` gives `updateUIView` more than the coordinator: - `context.environment`, the current `EnvironmentValues`, so the UIKit view can follow values such as a custom tint or the color scheme; - `context.transaction`, which tells you whether the change is animated; - from iOS 18, `animate(changes:completion:)`, which runs UIKit changes as part of the SwiftUI animation in progress. ## What not to do - **Do not create views in `updateUIView`.** Creating a new map on every update discards its state and is slow. - **Do not set layout properties yourself.** The documentation warns that SwiftUI fully controls the wrapped view's center, bounds, frame and transform, and setting them yourself is undefined behaviour. - **Do not keep state only in the UIKit view** if it must survive a change of identity; when identity changes SwiftUI dismantles the old view and makes a new one.

  • Why does a Coordinator that stores the representable from makeCoordinator() sometimes call an outdated onSelect closure?
    The coordinator is created once, but SwiftUI rebuilds the representable struct on every parent update, possibly with new closures or values. A coordinator that keeps the first copy keeps calling the first closure. Assign `context.coordinator.parent = self` at the top of `updateUIView` so the coordinator always holds the latest copy.
  • How does updateUIView read SwiftUI environment values such as the color scheme or an animation?
    Through its context: `context.environment` exposes the current `EnvironmentValues`, and `context.transaction` the current transaction, including any animation. From iOS 18 the context also has `animate(changes:completion:)`, which runs UIKit changes inside the SwiftUI animation in progress.
  • When does SwiftUI create a second UIKit view for the same representable type?
    When the representable loses its identity: it moves to a different branch of an if/else, its explicit `id(_:)` changes, or it leaves and re-enters the hierarchy. SwiftUI dismantles the old view and calls `makeCoordinator()` and `makeUIView(context:)` again, so no state stored only in the old view survives.

  • Creating a new UIKit view inside updateUIView on every update.
  • Making the representable struct itself the delegate of the UIKit view.
  • Assuming makeUIView runs again each time the parent body is recomputed.
  • Setting the wrapped view's frame or bounds by hand from the representable.
  • Thinking dismantleUIView is an instance method that can read the representable's properties.