Fix: Cannot Read View Size in SwiftUI

Written by

in

Quick answer: SwiftUI doesn’t expose a view’s rendered frame directly. To read width or height, place a GeometryReader in the view’s background or overlay, then pass the size out via a @State property, a PreferenceKey, or (iOS 17+) the onGeometryChange modifier.

Why this happens

SwiftUI’s layout system is declarative: you describe what the UI should look like, and the framework calculates frames during a separate layout pass. Views don’t have a frame property you can read like UIView.frame in UIKit. The size of a view isn’t known until after SwiftUI has resolved all constraints, proposed sizes, and alignment guides. Because the layout pass runs asynchronously and can happen multiple times, there is no synchronous getter for a view’s dimensions.

Attempting to read a size too early (for example in onAppear before the layout pass finishes) returns .zero. The correct approach is to hook into the layout system itself—GeometryReader—and propagate the measured size back to your state using a mechanism that respects SwiftUI’s data flow (bindings, preferences, or the new onGeometryChange API).

How to fix it

1. Use GeometryReader in a background (iOS 13+)

The most common pattern is to attach a GeometryReader as a transparent background of the view you want to measure. On appear, the proxy reports the size of that background—which matches the view’s rendered size.

import SwiftUI

struct SizeReaderModifier: ViewModifier {
    @Binding var size: CGSize

    func body(content: Content) -> some View {
        content
            .background(
                GeometryReader { proxy in
                    Color.clear
                        .onAppear { size = proxy.size }
                        .onChange(of: proxy.size) { _, new in size = new }
                }
            )
    }
}

extension View {
    func readSize(into binding: Binding<CGSize>) -> some View {
        modifier(SizeReaderModifier(size: binding))
    }
}

// Usage
struct DemoView: View {
    @State private var textSize = CGSize.zero

    var body: some View {
        VStack {
            Text("Measured size: \(Int(textSize.width)) x \(Int(textSize.height))")
            Text("Hello, SwiftUI!")
                .font(.largeTitle)
                .readSize(into: $textSize)
        }
    }
}

Why this works: The background participates in the same layout pass as the content, so proxy.size reflects the final rendered dimensions. The onChange ensures updates if the view resizes (e.g., rotation, Dynamic Type).

2. Prefer onGeometryChange on iOS 17 / macOS 14+

Starting with iOS 17, SwiftUI provides a first-party modifier that eliminates the boilerplate:

struct DemoView: View {
    @State private var textSize = CGSize.zero

    var body: some View {
        VStack {
            Text("Measured size: \(Int(textSize.width)) x \(Int(textSize.height))")
            Text("Hello, SwiftUI!")
                .font(.largeTitle)
                .onGeometryChange(for: CGSize.self) { proxy in
                    proxy.size
                } action: { newSize in
                    textSize = newSize
                }
        }
    }
}

onGeometryChange runs after layout, avoids the Color.clear hack, and lets you transform the proxy into any Equatable value (size, frame, safe-area insets, etc.).

3. PreferenceKey for advanced scenarios (multiple children, coordinate spaces)

When you need to collect sizes from several sibling views or convert frames to a common coordinate space (e.g., aligning columns), a PreferenceKey is the robust solution:

struct SizePreferenceKey: PreferenceKey {
    static var defaultValue: [Int: CGSize] = [:]
    static func reduce(value: inout [Int: CGSize], nextValue: () -> [Int: CGSize]) {
        value.merge(nextValue(), uniquingKeysWith: { $1 })
    }
}

extension View {
    func tagSize(_ tag: Int) -> some View {
        background(
            GeometryReader { proxy in
                Color.clear
                    .preference(key: SizePreferenceKey.self, value: [tag: proxy.size])
            }
        )
    }
}

struct MultiMeasureView: View {
    @State private var sizes: [Int: CGSize] = [:]

    var body: some View {
        VStack {
            Text("First").tagSize(0)
            Text("Second line of text").tagSize(1)
            Text("Third").tagSize(2)
        }
        .onPreferenceChange(SizePreferenceKey.self) { sizes = $0 }
        .overlay(alignment: .topLeading) {
            Text(sizes.map { "\($0): \($1)" }.joined(separator: "\n"))
                .font(.caption)
                .padding()
                .background(.thinMaterial)
        }
    }
}

Each view tags its size with an integer key; the parent collects all sizes in a single preference update.

4. Overlay instead of background (when background is already used)

If the view already has a background (color, image, material), use .overlay with alignment: .center so the GeometryReader still adopts the content’s size:

Text("Label")
    .background(Color.yellow)          // existing background
    .overlay(alignment: .center) {     // measure on top
        GeometryReader { proxy in
            Color.clear
                .onAppear { print("Size:\(proxy.size)") }
        }
    }

How to prevent it

  • Default to onGeometryChange on iOS 17+; it’s maintained by Apple and handles edge cases (safe areas, coordinate spaces).
  • Avoid reading size in onAppear alone—always pair with onChange(of: proxy.size) or the preference/geometry-change callback to catch layout updates.
  • Don’t force layout with fixed frames just to get a size; let SwiftUI propose sizes naturally and measure the result.
  • Keep measurement code out of the view’s body—side effects (state writes) belong in onAppear, onChange, or preference callbacks to avoid “Modifying state during view update” warnings.
  • Test with Dynamic Type, rotation, and split view to ensure the measured size updates correctly.

FAQ

Why does GeometryReader in a VStack give me the whole screen width?

A GeometryReader expands to fill the space offered by its parent. Inside a VStack with default alignment, the stack offers the full width. Place the GeometryReader in a background/overlay of the specific child you want to measure, not as a sibling.

Can I get the frame in global coordinates instead of local size?

Yes. Use proxy.frame(in: .global) or proxy.frame(in: .named("MySpace")) inside the GeometryReader. With onGeometryChange, return proxy.frame(in: .global) from the transform closure.

Does measuring a view cause a second layout pass?

No. The GeometryReader in a background/overlay participates in the same layout pass. Writing the size to @State or a preference triggers a separate render pass, but layout itself runs only once per update cycle.

Summary

SwiftUI hides view frames by design. The supported way to read a rendered size is to let a GeometryReader adopt the view’s layout space—via background, overlay, or the new onGeometryChange modifier—and pipe the resulting CGSize or CGRect back into your state. Choose the modern onGeometryChange API when targeting iOS 17/macOS 14 or later; otherwise, the background + binding pattern remains reliable and widely used.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.