Chapter 45
Switching Layout with AnyLayout

Starting from iOS 16, SwiftUI provides AnyLayout and the Layout protocol for developers to create customized and complex layouts. AnyLayout is a type-erased instance of the layout protocol. You can use AnyLayout to create a dynamic layout that responds to users’ interactions or environment changes.

In this chapter, you will learn how to use AnyLayout to switch between vertical and horizontal layout.

Using AnyLayout

First, create a new Xcode project using the App template. Name the project SwiftUIAnyLayout or any other name you prefer. What we are going to build is a simple demo app that switches the UI layout when you tap the stack view. Figure 1 shows the UI layout for different orientations.

Figure 1. Switching between vertical and horizontal stacks using AnyLayout
Figure 1. Switching between vertical and horizontal stacks using AnyLayout

The app initially arranges three images vertically using VStack. When a user taps the stack view, it changes to a horizontal stack. With AnyLayout, you can implement the layout like this:

To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.

results matching ""

    No results matching ""