Sometimes it can be beneficial to change the layout depending on the device’s portrait or landscape orientation. To do this, we can use AnyLayout, which allows us to make the choice at runtime.
Let’s look at the code:
struct ContentView: View {
@Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
@Environment(\.verticalSizeClass) var verticalSizeClass: UserInterfaceSizeClass?
var body: some View {
let layout = horizontalSizeClass == .compact && verticalSizeClass == .regular ?
AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())
layout {
if horizontalSizeClass == .compact {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Image(systemName: "car")
.imageScale(.large)
.foregroundColor(.accentColor)
Image(systemName: "pencil")
.imageScale(.large)
.foregroundColor(.accentColor)
}
}
}
}
The Environment is a property wrapper that reads values from a view’s environment. In this case, we retrieve the horizontal and vertical size classes. The compact size class represents a smaller space, while regular represents a larger space. Therefore, when the horizontal size is compact and the vertical size is regular, we set the layout to vertical; conversely, when the horizontal size is regular, we set the layout to horizontal.
Therefore, for portrait orientation, we have:
On the other hand, for landscape orientation, we have:
Coding is fun!