skip to content

In SwiftUI, how do @ScaledMetric and the dynamicTypeSize environment value keep a now-playing header usable at the largest accessibility text sizes?

level: middleimportance: must knowfreq 64%

answer

  1. text scales, fixed numbers do not
  2. scale a number like a font
  3. relativeTo a text style
  4. isAccessibilitySize flips the axis

basics

~20 s

Text in text styles scales with Dynamic Type; fixed numbers do not. @ScaledMetric scales a number, such as an artwork size, along a text style's curve, and reading dynamicTypeSize lets a layout stack vertically when isAccessibilitySize is true.

solid answer

~40 s

Text set in a text style such as `.title2` or `.body` already follows the user's Dynamic Type setting; the parts that break are hard-coded numbers. `@ScaledMetric(relativeTo: .title2) var artworkSize: CGFloat = 56` turns a fixed artwork size into one that grows with the title beside it; the wrapped type must be a `BinaryFloatingPoint`, so `CGFloat` or `Double`, not `Int`. For structure, I read `@Environment(\.dynamicTypeSize)`: the values are ordered from `.xSmall` to `.accessibility5`, and `isAccessibilitySize` is true for the five accessibility sizes, which is where a side-by-side header usually has to stack vertically. I switch with `AnyLayout` so the children keep their identity, and I check the screen in a preview with `.dynamicTypeSize(.accessibility5)`.

code

swift · 32 lines
swift
import SwiftUI

struct NowPlayingHeader: View {
    @ScaledMetric(relativeTo: .title2) private var artworkSize: CGFloat = 56
    @Environment(\.dynamicTypeSize) private var dynamicTypeSize

    let title: String
    let artist: String

    var body: some View {
        let layout = dynamicTypeSize.isAccessibilitySize
            ? AnyLayout(VStackLayout(alignment: .leading, spacing: 8))
            : AnyLayout(HStackLayout(spacing: 12))

        layout {
            Image(systemName: "music.note")
                .resizable()
                .scaledToFit()
                .frame(width: artworkSize, height: artworkSize)
                .accessibilityHidden(true)
            VStack(alignment: .leading) {
                Text(title).font(.title2)
                Text(artist).font(.body)
            }
        }
    }
}

#Preview("Largest accessibility size") {
    NowPlayingHeader(title: "Evening Tide", artist: "A quartet")
        .dynamicTypeSize(.accessibility5)
}

go deeper

for a junior

Recall that text styles scale on their own, that @ScaledMetric scales numbers, and that you can preview a screen at a size with .dynamicTypeSize(.accessibility5).

for a middle

Explain how relativeTo: picks the scaling curve, why the value must be floating point, how DynamicTypeSize is ordered and which sizes isAccessibilitySize covers.

for a senior

Show how you find the hard-coded metrics that clip at large sizes, switch layouts with AnyLayout instead of rebuilding views, and treat any Dynamic Type cap as a reviewed exception.

for a principal

Argue for a team rule that every screen is checked at the largest accessibility size before merge, and for which components, if any, may cap Dynamic Type.

## What Dynamic Type scales, and what it misses **Dynamic Type** is the iOS setting that lets a person choose a larger or smaller text size, from extra small up to five extra-large **accessibility sizes**. SwiftUI applies it automatically to text that uses a **text style**: - `Text` with `.font(.body)`, `.font(.title2)` or any other `Font.TextStyle` scales with the setting. - `Font.custom(_:size:)` scales with the body text style, and `Font.custom(_:size:relativeTo:)` scales relative to the style you name. - `Font.custom(_:fixedSize:)` is documented as a fixed size that does not scale with Dynamic Type, so choose it only on purpose. What text styles do not reach is every **hard-coded number** around the text: a 56-point artwork frame, a 12-point gap, a 44-point button. At the largest sizes the text grows and those numbers stay put, so titles truncate next to a tiny icon, or rows overlap. ## @ScaledMetric: scaling a number `@ScaledMetric` is a property wrapper, available since iOS 14, that scales a numeric value with the current Dynamic Type size: ```swift @ScaledMetric(relativeTo: .title2) private var artworkSize: CGFloat = 56 ``` 1. The **wrapped value** (56) is the size at the default text size. 2. **`relativeTo:`** names the text style whose scaling curve to follow. Pick the style of the text the metric sits beside, so the icon and its title grow together. Without it, `init(wrappedValue:)` uses the default scaling. 3. The wrapper is a `DynamicProperty`, so it reads the view's environment and the view updates when the size changes. The generic parameter is constrained to **`BinaryFloatingPoint`**: `CGFloat` and `Double` work, and `@ScaledMetric var spacing: Int = 8` is a compile error ("generic struct 'ScaledMetric' requires that 'Int' conform to 'BinaryFloatingPoint'"). ## Reading the size to change structure Scaling numbers keeps proportions, but at accessibility sizes a side-by-side layout simply runs out of width. For that, read the size from the environment: ```swift @Environment(\.dynamicTypeSize) private var dynamicTypeSize ``` `DynamicTypeSize` (iOS 15) is an ordered enum with twelve cases: | Group | Cases | `isAccessibilitySize` | |---|---|---| | Standard sizes | `.xSmall`, `.small`, `.medium`, `.large`, `.xLarge`, `.xxLarge`, `.xxxLarge` | `false` | | Accessibility sizes | `.accessibility1` to `.accessibility5` | `true` | Because the enum is `Comparable`, Apple's own example writes `if dynamicTypeSize >= .accessibility1`, and `isAccessibilitySize` is the shorthand for that check. The default value is device-dependent, so never assume it. To switch the header from a row to a column, wrap the content in `AnyLayout(HStackLayout())` or `AnyLayout(VStackLayout(alignment: .leading))`. Apple's documentation for `AnyLayout` uses this exact case and says it changes the layout type without destroying the state of the subviews, which an `if`-`else` between two stacks would do. ## Symbols and bitmap images Not every image needs a metric. - An **SF Symbol** shown with `Image(systemName:)` takes its size from the current font, so `Image(systemName: "music.note").font(.title2)` grows with the title2 style without any extra code. - A **bitmap or a resizable image** in a fixed `frame` does not grow, which is exactly the case `@ScaledMetric` exists for. The artwork in a now-playing header is the classic example. - **Padding and spacing** beside large text often need scaling too. A 4-point gap that looks right at the default size can make text touch its icon at `.accessibility3`. ## Setting and capping the size The same name exists as a view modifier: - `.dynamicTypeSize(.accessibility5)` sets the size for a subtree. Its main use is a preview of the worst case. - `.dynamicTypeSize(...DynamicTypeSize.accessibility2)` limits the range a subtree may use. Apple's documentation notes that a range applied after a fixed value clamps it, and suggests `accessibilityShowsLargeContentViewer()` for views you limit this way. A cap is a design exception, not a fix. A list or a reading screen should grow without limit; a compact control bar might justify one. The older `sizeCategory` environment value is still in the SDK, but it is marked deprecated with a rename to `dynamicTypeSize`, so new code should not read it. ## A working routine - Use text styles for all text, and `@ScaledMetric` for every size that sits beside text. - Add a preview at `.dynamicTypeSize(.accessibility5)` for each screen with a dense layout. - Where the layout cannot fit, branch on `isAccessibilitySize` with `AnyLayout` rather than shrinking the text. - Treat a range cap as a reviewed exception, paired with the large content viewer where the control stays small.

  • When is it acceptable to cap Dynamic Type with dynamicTypeSize(...DynamicTypeSize.accessibility2)?
    Only for a view that truly cannot grow, such as a compact bar of controls, and then deliberately. Apple's documentation suggests considering `accessibilityShowsLargeContentViewer()` for views whose size is constrained this way, and warns that the large content viewer is not a replacement for proper Dynamic Type support, so a list or a reading screen should never be capped.
  • Why switch layouts with AnyLayout rather than an if-else between an HStack and a VStack?
    An if-else creates two branches with different structural identity, so crossing the threshold rebuilds the children and resets any state they own. `AnyLayout` wrapping `HStackLayout` or `VStackLayout` keeps one container whose layout changes, and Apple's documentation says it changes the layout type without destroying the subviews' state. The general mechanics of `AnyLayout` belong with custom layouts; here it is simply the right switch.
  • The environment also has sizeCategory; should new code read it?
    No. In the iOS 27 SDK, `sizeCategory` is marked deprecated with a rename to `dynamicTypeSize`, with no release number set yet. `DynamicTypeSize`, available since iOS 15, is ordered, so comparisons such as `>= .accessibility1` work, and it has `isAccessibilitySize`.

  • Believing a .frame(width: 56) image grows with Dynamic Type on its own
  • Declaring @ScaledMetric with an Int value type
  • Capping every screen's dynamicTypeSize to protect the layout
  • Thinking isAccessibilitySize is true for xxxLarge
  • Reading sizeCategory in new code instead of dynamicTypeSize