iPhone Duo: Runtime Hinge State and Dual-Screen Layout

iPhone Duo: Runtime Hinge State and Dual-Screen Layout

⚠️ Speculative Architecture & Preview: This article discusses future system iterations (e.g., iOS 27, Xcode 27) as conceptual planning and architectural design patterns. Technical details represent previews and proposals rather than finalized APIs.

iPhone Duo: Runtime Hinge State and Dual-Screen Layout

The fold on the iPhone Duo is not a launch-time configuration. Shipped apps regress on this device precisely because the iPhone Duo developer model treats foldState as a static trait read once at startup and never re-read until the next launch. That model survives the first fold by luck. The regression shows up around the third one, when a hinge-angle burst has re-entered the tree, re-run onAppear, and duplicated tasks — while the user’s hand is still moving.

sampleΔt (ms)foldStateangleDegreesmarked in the app tree
10.flat180.0baseline
2+11.halfFolded172.8bounds change; size-class branch flips
3+23.halfFolded158.4onAppear re-fires in the replaced leaf
4+39.halfFolded141.5.task starts a second catalogue load
5+58.halfFolded123.9grid cells re-measure; scroll anchor dropped
6+91.halfFolded101.6burst ends; dwell at rest

Figure 1 — One fold gesture as the runtime delivers it: roughly six angleDegrees samples inside a hundred milliseconds, then silence. The simulator interpolates the same two endpoints smoothly and shows none of this, which is why the defect is invisible until you install on hardware.

Wireframe of a hinged dual-screen layout: a stable layout pane on the left, a burst waveform on the right, a radiating hinge-state node at the fold center, and a runtime-state rail below the two panels. Symbols only, no text.

The Verdict

  • Model the Duo as an observable runtime dimension, not a launch-time size class. foldState and angleDegrees mutate continuously after launch, and every consumer in your layout graph must treat them that way or the second fold invalidates assumptions the first one happened to spare.
  • Debounce angle updates — but never debounce the posture. Coalesce the angleDegrees feed for effect-driven consumers; commit foldState transitions in the same run-loop turn. A debounce in front of posture classification is exactly what makes hinge-follow feel laggy.
  • Scope geometry to UIScene. UIScreen.main is ambiguous on a two-display device, and scene-scoped geometry (effectiveGeometry, isInteractivelyResizing, @SceneStorage) is the only coordinate space that means something when a fold hands you off between canvases.
  • Keep view identity stable across the fold. A posture branch swap destroys @State and re-runs onAppear/.task, duplicating load work and resetting in-progress input. Preserve identity, hoist the state, and make the work idempotent.
  • Test on device. The simulator does not reproduce the burst cadence, so the regressions this article describes are hardware-only until you take the debugging pass off the fold control.

The Fold Is Continuous, and “Once at Launch” Reads It Wrong

The first iPhone Fold guide mapped the API surface: foldState, angleDegrees, reserved regions, the multi-display handoff. What it could not teach — because it was published before launch — is that this surface is continuous runtime state, delivered on a cadence that contradicts every launch-time assumption you can build against.

A size class is a coarse, quasi-static trait. An app reads it, chooses a layout, and stays there until the user rotates or resizes. A fold is nothing like that. The hinge reports posture and angle while the transition is in progress — your tree receives six geometry-delivering updates before the gesture ends, and iOS 27.1’s own hinge guidance is explicit that the raw hinge angle is there to drive interactions and effects, not to be read as a final layout input. The layout-facing truth is what Apple shipped separately as arrangement and reserved-region APIs, which hand you the usable panes across the fold instead of leaving you to re-derive them from a moving number.

Treating foldState as “a size class I read at launch” is the trap. It inverts the dependency: the layout ends up owning the geometry, and the runtime state is a spectator. The predictable way to build dual-screen layout on the Duo is to make the runtime dimension the single source of truth and let every view subscribe to it.

A Fold Is a Burst, Not a Ramp

The burst in Figure 1 is not an artifact of a buggy sensor or an early point release. It is the device reporting hinge motion the way hardware actually delivers it: discrete samples, densely clustered while the hinge is moving, abruptly silent once it rests. Three consequences follow:

  1. The transition is over before your throughput finishes re-branching. Whatever you kick off inside a fold transition must complete within the gesture or it stacks with the next posture change.
  2. The value you would branch on travels through a range, not a single point. Reading angleDegrees once and committing is reading noise; the useful signal is the classified state with hysteresis, not an instantaneous sample.
  3. Re-entry is not a rotation. An orientation change is a size mutation inside the same identity. A fold transition in SwiftUI can be a structural replace — the branch flips, the node is torn down, and onAppear runs again. That is the actual source of the duplication.

The simulator fold control in Xcode 27.1’s Device Hub interpolates between open and closed. It will show you whether the branches exist. It will not reproduce the cadence, because it has no hinge — it has a slider. Everything below is written for the signal a slider cannot fake.

The Hidden Cost: Layout Re-Entry Runs the Side Effects Again

The explicit cost nobody budgets for: task duplication and list re-entry on every fold transition. The mechanics come from SwiftUI identity, not from the Duo. if/else on posture creates a ConditionalContent whose two arms are distinct structural identities; flipping the branch destroys the old node, resets its @State bank, and re-fires appearance-driven modifiers. On a normal device that cost only shows up when a screen genuinely leaves and returns. On the Duo it fires mid-gesture, twice — once opening, once closing — and it re-runs everything you attached to onAppear and .task.

// Regressed build. The fold passes, then the catalogue reloads on every
// transition because the branch swap re-created the leaf identity.
struct LibraryRoot: View {
    @Environment(DuoRuntime.self) private var duo

    var body: some View {
        // Structural identity: leaving .flat for .halfFolded destroys the
        // flat node, so @State inside it resets and onAppear / .task fire
        // again. Two folds later the network layer has a third in-flight
        // request for the same page.
        if duo.foldState == .halfFolded {
            LibraryGrid()     // .task { try? await loadPage(1) } inside
        } else {
            LibraryList()
        }
    }
}

The .task inside the branches re-runs because it is scoped to a node whose lifetime just ended. The fix is not “guard against double-loading somewhere”; the guard has to live above the branch, and the identity of the branch has to stop changing.

Model the Duo as an Observable Runtime Dimension

Put the runtime surface in an @Observable model that owns classification, debouncing, and hysteresis, and give views exactly two ways to observe it: the committed foldState for layout branching and a coalesced angleDegrees for effects. Nothing in the tree reads the raw hinge stream directly.

import SwiftUI
import Observation

/// The fold as an observable runtime dimension. Layout branches on
/// `foldState`; effect consumers read the coalesced `angleDegrees`. No view
/// ever sees the raw hinge stream.
@MainActor @Observable
final class DuoRuntime {
    private(set) var foldState: FoldState = .flat
    private(set) var angleDegrees: Double = 180

    private var angleTask: Task<Void, Never>?
    private var latestAngle: Double = 180

    /// Called from .onHingeChange on the main actor.
    func hingeChanged(_ context: DeviceHingeContext) {
        guard let hinge = context.hinge else { return }  // nil = hingeless device

        let angle = hinge.angle.degrees

        // Fast path — commit the posture in the same turn. Debouncing this is
        // what made the first version feel laggy: the classification trailed
        // the gesture and the screen visibly "caught up" after the burst, so
        // users judged the whole app slow even though layout was correct.
        guard let next = FoldState(status: hinge.status, angle: angle) else {
            return
        }
        if next != foldState {
            foldState = next
        }

        // Slow path — coalesce angle-driven effects. Bursts deliver ~6 raw
        // samples in 100 ms; parallax and dimming want one value per frame,
        // not six invalidations of the subtree in the same run-loop turn.
        latestAngle = angle
        angleTask?.cancel()
        angleTask = Task { @MainActor [self] in
            try? await Task.sleep(for: .milliseconds(48))
            guard !Task.isCancelled else { return }
            self.angleDegrees = self.latestAngle
        }
    }
}

The classification needs hysteresis, because the raw stream is noisy within a few degrees of a rest position. A single threshold flaps between postures while the hinge sits on the boundary — the UI oscillates, and every flap is a re-entry.

extension FoldState {
    /// Maps the hinge status + angle to a posture with a 12-degree band.
    /// "Passed 165 by a margin" replaces "is currently 164.8".
    init?(status: DeviceHinge.Status, angle: Double, previous: FoldState = .flat) {
        switch status {
        case .closed:
            self = .closed
        case .fullyOpen:
            self = angle >= 165 ? .flat : previous   // dwell band near flat
        case .partiallyOpen:
            if angle >= 118 {
                self = (previous == .flat || previous == .closed) ? .tabletop : previous
            } else {
                self = previous == .tabletop ? previous : .book
            }
        case .unknown:
            return nil
        }
    }
}

The model is testable without hardware because the hinge input is reduced to one method. Previews and unit tests inject a scripted context sequence and assert on posture transitions and the coalesced feed — the same harness works on simulator and device, which is the whole point of keeping the raw stream out of the views.

Scope Geometry to UIScene, Not UIScreen

The Duo has two displays. UIScreen.main is deprecated and, on a two-display device, ambiguous: it answers with whichever canvas is front-most at query time, which is usually the wrong one by the time your layout math finishes. Geometry has to be scene-scoped, and the scene is where the fold shows up. On the UIKit side, UIWindowScene exposes exactly the runtime dimension you need.

// Scene-scoped geometry. UIScreen.main was the first casualty: on Duo two
// scenes share one process and the "main" screen returns the canvas that is
// front-most at query time — wrong for the scene behind it.
final class SceneGeometryCoordinator: NSObject, UIWindowSceneDelegate {
    private let duo = DuoRuntime.shared
    private var lastConfirmedSize = CGSize.zero

    func windowScene(
        _ windowScene: UIWindowScene,
        didUpdateEffectiveGeometry previousGeometry: UIWindowScene.Geometry
    ) {
        guard let geometry = windowScene.effectiveGeometry else { return }

        // isInteractivelyResizing is the burst tell: while the hinge is held
        // mid-fold, the scene streams resize updates faster than layout can
        // settle. Cheap layout rides along; anything expensive waits for the
        // gesture to rest. This is where the simulator lies — it reports a
        // clean begin/resize/end, so the guard never fires in CI.
        guard !geometry.isInteractivelyResizing else { return }

        let size = geometry.coordinateSpace.bounds.size
        guard size != lastConfirmedSize else { return }

        duo.sceneResized(to: size)
        lastConfirmedSize = size
    }
}

On the SwiftUI side the rules are simpler: size views from their container (view.bounds, containerRelativeFrame, GeometryReader at the leaf), read @Environment(\.displayScale) instead of the screen, and keep in-progress state in @SceneStorage, which is explicitly per-scene. A fold can tear a scene down and reconnect it without terminating the process; a scene reconnect reloads @SceneStorage, while app-wide storage would let one canvas clobber another’s draft. Scoped to the scene, the draft survives the fold because it is restored against the scene it belongs to.

Keep View Identity Stable Across the Transition

The durable fix for the re-entry problem is to make the branch stop being a structural identity switch. Two moves, in combination:

First, defer the branch as far down the tree as possible and keep the leaf’s identity constant. When the layout genuinely needs different arrangements across the fold, let the arrangement container own that decision — the slots keep their identity while the pane geometry changes, which is exactly what the arrangement/reserved-region APIs are for:

// Dedicated folding container: ArrangementView owns the split/overlay
// decision from the runtime reserved regions, so we never branch on angle
// ourselves. The content slot keeps its structural identity across the
// transition; only the pane geometry changes.
ArrangementView(primary: { LibraryList() }, secondary: { ReaderPanel() })
    .arrangementViewStyle(.split)
    .axes(.horizontal)

// Learn which panes actually exist at this instant. Division regions are
// not permanent — the hinge region is active only while folded and is
// zero-width when flat, so layout must handle it appearing and vanishing.
GeometryReader { proxy in
    let division = proxy.reservedRegions(kind: .division)
    // inset content from the active seam; ignore it when empty
}

Second, make the appearance-driven work idempotent and hoist it above the branch. onAppear and .task are visibility and lifetime events, respectively, and on the Duo neither is a reliable “ran once” signal. Key the task to the posture you actually react to, and guard on a marker — not on “is the data empty,” which is true both when nothing has loaded and when a refresh is mid-flight:

// Hoisted, idempotent load. .task re-runs on each fold transition; the
// marker is what stops it from duplicating work, and it survives because it
// lives in the model above the branch.
LibraryView(...)
    .task(id: duo.foldState) {
        await catalogue.loadIfNeeded()
    }

@MainActor
func loadIfNeeded() async {
    // Guarded by a page marker, not `pages.isEmpty`: mid-fold the array is
    // already populated the third time this fires, so isEmpty would let a
    // partial refresh slip through. The marker is stable until the scene is
    // torn down.
    guard loadedPage == nil else { return }
    loadedPage = .inFlight
    do {
        let page = try await api.cataloguePage(1)
        pages.replace(with: page)
        loadedPage = .loaded(page)
    } catch {
        loadedPage = .failed(error)
    }
}

This is the point where “predictable” is earned. The views re-render as many times as the burst requires, but the work runs once, the input is preserved, and the scroll position survives because the identity survived. The layout cost of the fold is a re-layout; with stable identity it is never a re-run of your business logic.

Test On Device, Not the Folding Simulator

The simulator’s fold control is a slider between two static geometries. It validates that your branches exist and that both panes are reachable. It cannot validate cadence, and cadence is where every regression in this article lives. The discipline that catches them:

  1. Log the burst. A debug assertion that asserts the maximum samples-per-100-ms and the dwell-after-rest pattern. On simulator this passes trivially; on device it will teach you the cadence your gesture actually produces.
  2. Test the full flow, not the frame. Fold mid-task: text field focused, catalogue mid-load, scroll anchored. Assert no duplicate request, no input reset, no anchor drop. A snapshot-only suite misses all of it.
  3. Drive the fold on hardware with a UI test. The fold control in Device Hub is for exploration; automated fold sequences belong on a physical unit in CI, gated behind a device-only configuration so the flaky-free simulator run stays green.
  4. Ship the audit result. Every screen that hosts a .task or a long-lived @State outside a NavigationStack gets a fold-transition test. The cheap way to find the screens that need it is the scene-scoped audits in the UIKit adaptivity checklist, which mark the UIRequiresFullscreen and single-window assumptions that the Duo turns into failures.

The hidden cost of treating the fold as a launch-time size class was never a missing layout — the layout adapts. The cost is that the runtime state you ignored is the same state that re-runs your effects, and by the time the duplicate tasks land you have already told the user the app is unreliable. Model the Duo as an observable runtime dimension, debounce the angle without debouncing the posture, scope geometry to the scene, keep identity stable, and the fold becomes a re-layout instead of a re-launch.

References & Documentation

Ready for more depth?

Master these concepts with our structured technical roadmap.

View Roadmap