Skip to main content

How to dynamically change between VStack and HStack

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to dynamically change between VStack and HStack 관련

SwiftUI by Example

Back to Home

How to dynamically change between VStack and HStack | SwiftUI by Example

How to dynamically change between VStack and HStack

Updated for Xcode 15

New in iOS 16

SwiftUI's AnyLayout struct allows us to switch between HStack and VStack freely, based on whatever environment context we want to take into account – just remember to use the Layout-conforming variants of each.

For example, we might want to show a group of images horizontally when we're in a regular horizontal size class, or vertically otherwise, like this:

struct ContentView: View {
    @Environment(\.horizontalSizeClass) var horizontalSizeClass

    var body: some View {
        let layout = horizontalSizeClass == .regular ? AnyLayout(HStackLayout()) : AnyLayout(VStackLayout())

        layout {
            Image(systemName: "1.circle")
            Image(systemName: "2.circle")
            Image(systemName: "3.circle")
        }
        .font(.largeTitle)
    }
}

Download this as an Xcode projectopen in new window

Tip: Unlike using AnyView, AnyLayout doesn't incur any performance impact, and won't discard any of the state of its child views.

Alternatively, we could flip the axis when the user's Dynamic Type size goes beyond a certain size:

struct ContentView: View {
    @Environment(\.dynamicTypeSize) var dynamicTypeSize

    var body: some View {
        let layout = dynamicTypeSize <= .xxxLarge ? AnyLayout(HStackLayout()) : AnyLayout(VStackLayout())

        layout {
            Image(systemName: "1.circle")
            Image(systemName: "2.circle")
            Image(systemName: "3.circle")
        }
        .font(.largeTitle)
    }
}

Download this as an Xcode projectopen in new window

As well as VStackLayout and HStackLayout, you can also use ZStackLayout and GridLayout.

Tips

Any grid rows that are used in non-grid layouts don't do anything – they become the same as using Group.

Similar solutions…
How to automatically switch between HStack and VStack based on size class | SwiftUI by Example

How to automatically switch between HStack and VStack based on size class
How to create stacks using VStack and HStack | SwiftUI by Example

How to create stacks using VStack and HStack
How to dynamically adjust the appearance of a view based on its size and location | SwiftUI by Example

How to dynamically adjust the appearance of a view based on its size and location
How to dynamically adjust the color of an SF Symbol | SwiftUI by Example

How to dynamically adjust the color of an SF Symbol
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks

이찬희 (MarkiiimarK)
Never Stop Learning.