SECRET OF CSS

The Layout Protocol in iOS 16. A practical look at the new protocol… | by Mark Lucking | Oct, 2022


A practical look at the new protocol introduced in SwiftUI

Photo by Esther Jiao on Unsplash

When I started coding, there were no frameworks to speak of. When you wanted to plot a circle on the screen, it took dozens or more lines of code than today. As science has developed, the concept of abstraction and frameworks has become the way forward.

Today, if I want to draw a circle using the SwiftUI framework, it takes just a couple of lines. It is good, but there is a price to pay; the higher the abstraction, the less flexibility you have, a trade-off.

When Apple launched SwiftUI, one of the goals was to make the layout of screens far easier than it has been for the past two decades with UIKit. It introduces three primary containers to lay out your windows: HStack, VStack, and ZStack. But for some, it was too high a price to do the layouts they had gotten used to in UIKit. They looked complex and messy in SwiftUI.

Apple has tried to address this by introducing the layout protocol, exposing the underbelly of those principle containers so that you can change how they behave. Join me in this article to look at some practical uses and implementations of this new protocol to let us create our containers with their own layout rules.

Let me start with this template in which I can switch between different layouts, defining new ones as I go along:

What your looking at here is a view on which you can select any of the standard layouts and move between them using the layout protocol.

Moving between different containers with the layout protocol in SwiftUI

So far, nothing new here.

Let us add some code to create a new layout. What I want to do is have my four views in a square. Within the layout protocol, I need to define two methods. This is the basic code:

A simple example of the layout protocol

Now, add this to the enum Algo and try it out:

Switching between the standard views and the custom one

The beauty here in the abstraction — to do this without the layout protocol is possible, but the code would be far more complex.

But, I know what you are thinking, they are not the corners. I want to place the views in the corners. Here is another version of the same code:

This places the views in the corners, as you might expect. Note that I set a border around it so that you can see what is happening better as I switch containers.

Switching between the standard views and the custom one

Of course, if you watched the WWDC20 video on this, they do an even more complex layout — one based on a circle. Here is the code behind that:

This animated GIF shows what it looks like.

Switching between the standard views and the custom one

All of which brings me to the end of this tour. I hope you learned something as you read through it; I certainly did writing it.



News Credit

%d bloggers like this: