How do I create a custom AnyLayout of two hstacks?
Asked on 10/17/2024
1 search
To create a custom AnyLayout
of two HStack
s in SwiftUI, you can use the AnyLayout
type to dynamically switch between different layouts based on certain conditions, such as accessibility settings. Here's a general approach based on the context provided:
-
Define a Dynamic Layout: Use the
AnyLayout
type to define a layout that can switch between anHStack
and another layout (likeVStack
) based on conditions such as accessibility settings. -
Implement the Layout: In your SwiftUI view, use the
AnyLayout
to apply the desired layout. For example, you can switch between anHStack
and aVStack
depending on the text size or other conditions.
Here's a simplified example:
struct CustomLayoutView: View {
@Environment(\.dynamicTypeSize) var dynamicTypeSize
var body: some View {
let dynamicLayout = dynamicTypeSize.isAccessibilityCategory ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())
dynamicLayout {
HStack {
Image(systemName: "star")
Text("Hello, World!")
}
HStack {
Image(systemName: "moon")
Text("Goodnight, Moon!")
}
}
}
}
In this example, the dynamicLayout
switches between an HStack
and a VStack
based on the dynamicTypeSize
. This allows the layout to adapt dynamically to different text sizes, which is particularly useful for accessibility.
For more detailed guidance, you can refer to the session Get started with Dynamic Type (06:00) which covers dynamic layouts in SwiftUI.

SwiftUI essentials
Join us on a tour of SwiftUI, Apple’s declarative user interface framework. Learn essential concepts for building apps in SwiftUI, like views, state variables, and layout. Discover the breadth of APIs for building fully featured experiences and crafting unique custom components. Whether you’re brand new to SwiftUI or an experienced developer, you’ll learn how to take advantage of what SwiftUI has to offer when building great apps.

Demystify SwiftUI containers
Learn about the capabilities of SwiftUI container views and build a mental model for how subviews are managed by their containers. Leverage new APIs to build your own custom containers, create modifiers to customize container content, and give your containers that extra polish that helps your apps stand out.

Design Live Activities for Apple Watch
Starting in watchOS 11, Live Activities from your iOS app will automatically appear in the Smart Stack on a connected Apple Watch. Learn how to optimize the layout of your Live Activity for the wrist, and provide the right level of information and interactivity at the right time.