iOSDevie

Share this post

How to Use SwiftUI AnyLayout

www.iosdevie.com

How to Use SwiftUI AnyLayout

Dynamically switch between views without recomposing child views

Anupam Chugh
Jul 7, 2022
Share this post

How to Use SwiftUI AnyLayout

www.iosdevie.com

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
Show hidden 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)
}
}
view raw SwiftUI-AnyLayout.swift hosted with ❤ by GitHub

iOSDevie is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.

Share this post

How to Use SwiftUI AnyLayout

www.iosdevie.com
Comments
TopNewCommunity

No posts

Ready for more?

© 2023 Anupam Chugh
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing