Logo for tanaschita.com

Understanding SwiftUI's ViewThatFits container

Learn to build adaptive layouts with SwiftUI's ViewThatFits container.

27 Jun 2022 · 2 min read

Starting with iOS 16, SwiftUI provides a new layout container ViewThatFits which helps us build adaptive layouts.

The ViewThatFits container allows 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 might benefit us.

Imagine we get a list of messages we want to display under each other. If a message fits in one line, we just show it. If it doesn't fit, we want to show only a part of that message and a button to open the full message. Something like this:

20220627 swiftui viewthatfits example

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 in
HStack() {
Image(systemName: "info.circle.fill")
ViewThatFits {
Text(message)
.fixedSize()
HStack {
Text(message)
.lineLimit(1)
Button("More") {
// Present full message
}
}
}
}
}
}
}

As shown in the example above, we provide the ViewThatFits container with two views, a Text view and an HStack which contains a Text and a Button view:

ViewThatFits {
Text(message)
.fixedSize()
HStack {
Text(message)
.lineLimit(1)
Button("More") {
// Present full message
}
}
}

As a first step, the ViewThatFits container checks, if the Text view fits into its parent container. Since the first message fits, it just stops here in shows the message.

Note that by applying the fixedSize modifier, we tell the Text view not to get wrapped or truncated.

When the longer second message comes in - which doesn't fit - the ViewThatFits container goes to the next view we provided, the HStack. The content of the HStack is designed to always fit, since the text is now allowed to be truncated, so the container picks that view and shows the truncated text alongside with a button to the user.

Newsletter

Like to support my work?

Say hi

Related tags

Articles with related topics

Latest articles and tips