Member-only story

How to Obtain View Dimensions in SwiftUI

fatbobman ( 东坡肘子)
4 min read6 days ago

--

TL;DR: Use GeometryReader, onGeometryChange , visualEffect, or containerRelativeFrameto dynamically retrieve and respond to view dimensions in SwiftUI. Each method caters to specific use cases and levels of customization.

Background

Dynamically retrieving the dimensions of a view is a common requirement in SwiftUI, especially in scenarios where layouts need to respond to size changes. This article introduces several methods to obtain view dimensions and their applicable use cases.

Stay ahead with the latest updates and deep insights on Swift, SwiftUI, Core Data, and SwiftData. Subscribe to Fatbobman’s Swift Weekly to get exclusive articles, tips, and curated resources delivered straight to your inbox every week.

For even more valuable content and in-depth tutorials, visit my blog at fatbobman.com — your go-to destination for all things Swift and Apple development.

Using GeometryReader

GeometryReader is a highly adaptable method compatible with all SwiftUI versions. It is often used with overlay or background to avoid interfering with the main view's layout.

Example Code

blueRectangle
.background(
GeometryReader { proxy in
Color.clear // Create a transparent view matching the main view's dimensions
.task(id: proxy.size) {
size = proxy.size // Retrieve a
}
)

Features

  • Encapsulates size retrieval logic within background, ensuring no impact on the main view's layout.
  • Uses task(id:) to fetch dimensions immediately when the view loads and update them when proxy.size changes.

Using onGeometryChange

Starting from iOS 16, onGeometryChange provides a more concise way to monitor size changes.

Example Code

struct SizeDemo: View {
@State var size: CGSize?
var

--

--

fatbobman ( 东坡肘子)
fatbobman ( 东坡肘子)

Written by fatbobman ( 东坡肘子)

Blogger | Sharing articles at https://fatbobman.com | Publisher of a weekly newsletter on Swift at http://weekly.fatbobman.com

No responses yet

Write a response