Member-only story

AnyLayout in SwiftUI

Nicola De Filippo
2 min readNov 15, 2024

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! If you like my post, i have a newsletter https://swiftuiblog.substack.com

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Nicola De Filippo
Nicola De Filippo

Written by Nicola De Filippo

Software Engineer and Entrepreneur

No responses yet

Write a response