< How to stop system gestures from interfering with your own | How to create a custom layout using the Layout protocol > |
Updated for Xcode 14.2
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 project
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 project
As well as VStackLayout
and HStackLayout
, you can also use ZStackLayout
and GridLayout
.
Tip: Any grid rows that are used in non-grid layouts don’t do anything – they become the same as using Group
.
SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.