iOS 16: Any Layout
In the past, it was always difficult to react dynamically to changing TypeSizes. For example, if you wanted to use either a horizontal or vertical layout depending on the TypeSize, the code looked like this:
With the help of AnyLayout you can solve this problem more elegantly, more about this in a moment.
First a short explanation what AnyLayout is:
With the help of AnyLayout you can dynamically change the type of a layout without destroying the state of the view. With this you can change a layout depending on the current Dynamic Type setting, for example from a HStack to a VStack.
The types, between which you want to change, must implement only the protocol Layout. Now if you want to switch between horizontal and vertical stacks as described above, you can use HStackLayout and VStackLayout, these are variants of the standard elements that already have the Layout protocol implemented.
With this knowledge, we can now make our code example from above a bit more elegant and, most importantly, dynamic.
Here is an example:
Now our view reacts dynamically to the changes of the dynamicTypeSize without having to determine how to configure our State variable as above. Up to a dynamic size of medium a HStack is used, if it is larger than medium a VStack is automatically used or its layout variants.
Of course you can also write your own layouts. Just implement the Layout protocol.
It contains two methods that need to be implemented:
1. sizeThatFits(proposal:subviews:cache:)
- returns the calculated size of the assembled layout
2. placeSubviews(in:proposal:subviews:cache:)
- places all subviews in the container of the layout
Through AnyLayout, Apple has created a way to customize its user interface with just a few lines of code, creating an even more flexible UI.
If you are interested in more iOS 16 feature videos, check out the following playlist.