SwiftUI Field Guide

Ideal Size

Every view has an ideal size. (For those familiar with Auto Layout, this is very similar to the view's intrinsic content size.) If we want to render a view at its ideal size, we can use the fixedSize modifier. This modifier proposes nil for both dimensions, which means the view will render at its ideal size.

Below, we can see some of the default behaviors: All the built-in shapes have an ideal size of 10×10, which is a platform default for many views. A text's ideal size is the bounding box of the rendered text without any word wrapping, and an image's ideal size is its underlying point size.

Code
Rectangle()    .fixedSize()
Preview
200

We can also return a custom ideal size using a flexible frame's idealWidth and idealHeight parameters. This is only used when a view gets proposed a nil value for the respective dimensions. When the fixed size modifier is enabled, we can see the view always renders at its ideal size, and when it's disabled, the rounded rectangle will fit itself into the proposed space.

Code
RoundedRectangle(cornerRadius: 5)    .foregroundStyle(.purple)    .frame(idealWidth: 100, idealHeight: 40)    .fixedSize()    .padding()
Preview
200

The ideal size of a view is used in a number of different places. Sometimes, we want a view to render at its ideal size, regardless of its proposal, and we can use fixedSize for that. When we use an aspect ratio modifier without an explicit ratio, the modifier uses the view's ideal size to compute the aspect ratio. When we use a scroll view, views will also render at their ideal width, ideal height, or ideal size (depending on the scroll view's configuration).