https://kean.blog/post/swiftui-layout-system

Everything about SwiftUI is new. And the layout system is no exception. SwiftUI no longer uses Auto Layout, gone all of the cruft introduced over the years. SwiftUI has a completely new layout system designed from the ground up to make it easy to write adaptive cross-platform apps.

I have always been fascinated by the layout systems. I built an open-source UIStackView replacement, designed a convenience API on top of Auto Layout (granted, many people did). I also have experience working with the layout systems on the web, including Flexbox. I can’t be more excited to dig deep into the SwiftUI layout system to see what it has to offer.

Layout Basics

Let’s start with the most basic “Hello World” example.

This is the code that gets generated when you select File / New File... / SwiftUI View in Xcode.

The moment you open the preview, you are already experiencing the layout system. The blue box in the preview editor indicates the bounds of the ContentView on screen. The bounds of the view are the same as its body, the text, which is at the bottom of the view hierarchy1. And finally, the root view which in this case has the dimensions of the device minus the safe area insets.

Safe Area

Safe area helps you place your views within the visible portion of the overall interface. In the example, the safe area of an interface excludes the status bar area. In SwiftUI, you are in the safety zone by default. You can still lay views out outside the safe area using the following modifier:

Text("Hello World")
    .edgesIgnoringSafeArea(.all)

The top layer of any custom view, like ContentView, is layout neutral. Its bounds are defined by the bounds of its body, in this case, Text. For the purposes of layout, you can treat the custom ContentView and Text as the same view. Now how did SwiftUI establish the bounds of the ContentView and why did it it position it in the center of the root view? To understand this, we need to understand how SwiftUI layout system works.

Layout Process

There are three steps in SwiftUI layout process.

1. Parent Proposes Size for Child

First, the root view offers the text a proposed size – in this case, the entire safe area of the screen, represented by an orange rectangle.

2. Child Chooses its Size

Text only requires that much size to draw its content. The parent has to respect the child's choice. It doesn't stretch or compress the child.

3. Parent Places Child in Parent’s Coordinate Space

And now the root view has to put the child somewhere, so it puts in right in the middle.