How to Use SwiftUI AnyLayout
Dynamically switch between views without recomposing child views
SwiftUI for iOS 16 introduced AnyLayout
— a struct to switch between type-erased layouts without losing the state of the subviews. It works with VStack
and HStack
like a charm — doesn’t work with ZStack
though.
While ViewThatFits
allowed SwiftUI choose the view for us, AnyLayout
gives you back some control over the customization
Creating transition effects without using transitions and geometry effects was never easier than this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct SwitchLayouts : View{ | |
@State private var switchStack: Bool = false | |
var body: some View{ | |
let layout = switchStack ? AnyLayout(HStack()) : AnyLayout(VStack()) | |
VStack{ | |
Button { | |
self.switchStack.toggle() | |
} label: { | |
Text("Switch") | |
} | |
layout { | |
RoundedRectangle(cornerRadius: 20) | |
.fill(.orange) | |
RoundedRectangle(cornerRadius: 20) | |
.fill(.blue) | |
} | |
.frame(width: 200, height: 200) | |
} | |
.padding() | |
.animation(.default, value: self.switchStack) | |
} | |
} |