How to dynamically change between VStack and HStack
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)
}
}
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)
}
}
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
.