New in SwiftUI 4: ViewThatFits

DevTechie
DevTechie
Published in
3 min readJun 18, 2022

--

Photo by Annie Spratt on Unsplash

ViewThatFits is a container view introduced with SwiftUI 4 and iOS 16. ViewThatFits holds collection of child views and displays a view depending upon the available size.

It does so by evaluating child views in the order they are defined and selects the child view whose size is ideal to fit in within the constrained space.

We provide views in the order we prefer, meaning we define in the order of largest to smallest view and ViewThatFits picks a child view depending upon the space provided by parent view.

This will get clear with an example. We will create a view which will display two Text views and a ViewThatFits container view.

ViewThatFits container view will contain two child views, both of them will contain buttons. One will contain buttons in VStack and other child view will contain buttons in HStack.

struct ContentView: View {

var body: some View {
VStack {
Text("DevTechie")
.font(.largeTitle)
Text("ViewThatFits is a container view introduced with SwiftUI 4 and iOS 16. ViewThatFits holds collection of child views and displays a view depending upon the available size. It does so by evaluating child views in the order they are defined and selects the child view whose size is ideal to fit in within the constrained space. We…

--

--