Mastering SwiftUI Layouts with ViewThatFits

Saeid Rezaeisadrabadi
3 min readJan 29, 2024

--

In this story, I want to talk about ViewThatFits, it is a powerful tool that often remains unexplored. In this story, we'll unravel its capabilities, providing insights into its significance and demonstrating how it can be leveraged to fine-tune your SwiftUI layouts.

Generated by AI

Introduction

ViewThatFits is a new view introduced and is available from iOS 16 onwards, it simplifies the creation of responsive layouts. It is a view that adapts to the available space by providing the first child view that fits.
Using ViewThatFits is elementary. You don’t need to manually measure available space or calculate if the particular view fits into the available space. All you need to do is create an instance of the ViewThatFits view and place it in its ViewBuilder closure. ViewThatFits automatically measures available space and the size of its children and takes the first view that perfectly fits the available space.

How to use

Here is an example of how to use ViewThatFits :

VStack {
ViewThatFits(in: .horizontal) {
Text("Full Brand Name")
Text("Short Name")
Text("Name")
}
.frame(width:150)
}

I set a manual width for my parent for illustrative purposes.

Width:150
Width:100
Width:50

As you can see, ViewThatFits selects a child view based on the available width.

By default, ViewThatFits considers all the available space, but you can set the particular axis you need to measure. For example, it might be a horizontal or vertical axis.

It’s crucial to note that ViewThatFits utilizes the first view that fits the available space. This implies that you should typically arrange your views from the largest to the smallest.

Conclusion

In conclusion, our exploration of ViewThatFits unveils its potential as a dynamic tool for crafting responsive layouts in SwiftUI. As a new addition available from iOS 16 onwards, ViewThatFits simplifies the complex task of adapting views to available space. The flexibility it offers in automatically measuring available space and selecting the first child view that fits makes it an invaluable asset for SwiftUI developers.
A key takeaway is the importance of ordering views from the largest to the smallest. This ensures that ViewThatFits selects the most suitable view, optimizing the use of available space effectively.

--

--

Saeid Rezaeisadrabadi
Saeid Rezaeisadrabadi

Written by Saeid Rezaeisadrabadi

Over 8 years of experience in iOS software development

Responses (1)