Learn to build adaptive layouts with SwiftUI's ViewThatFits container.
Understand how SwiftUI's ViewThatFits container works.
26 May 2025 · 3 min read
SwiftUI's ViewThatFits container helps us build adaptive layouts by allowing us to provide multiple views while automatically picking the first one which fits into available space.
Let's directly jump into an example to see how the container works.

Consider a scenario where you need to display a list of messages. If a message fits within a single line, we just display it fully. If it doesn't fit, we want to show a truncated version and a "more" button to open the full message. Something like this:
As we can see above, the first message fits into the available space, so we don't need the button. The second line only shows a part of the message with a button to show the full message.
To achieve this result, the ViewThatFits comes in handy. We just need to provide two different views, one that only contains the text and one that contains the text and the button. The ViewThatFits container will automatically pick the right one for us.
var body: some View {VStack(alignment: .leading, spacing: 10) {ForEach(messages, id: \.self) { message inHStack() {Image(systemName: "info.circle.fill")ViewThatFits {Text(message).fixedSize()HStack {Text(message).lineLimit(1)Button("more") {// Present full message}}}}}}}
In this example:
- The first view is a Text view with the .fixedSize() modifier, ensuring the text is not truncated.
- The second view is an HStack containing a truncated Text view and a "more" Button.
ViewThatFits evaluates these views in order and selects the first one that fits within the available space. If the first view doesn't fit, it proceeds to the next one. This approach allows for dynamic and responsive layouts.
ViewThatFits determines which view to display based on the "ideal size" of each child view. The ideal size refers to the size a view would occupy if it had unlimited space. By default, ViewThatFits considers both horizontal and vertical axes when evaluating the ideal size. However, we can specify which axis to consider by using the in: parameter. In our case, we are looking for a horizontal evaluation:
ViewThatFits(in: .horizontal) {Text(message).fixedSize()HStack {Text(message).lineLimit(1)Button("more") {// Present full message}}}
In this case, ViewThatFits will only consider the horizontal axis when determining which view to display.



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



