Created
January 18, 2022 21:33
-
-
Save richy486/a1c177fb705917f31a94a923c2807228 to your computer and use it in GitHub Desktop.
Animate between container views with `matchedGeometryEffect`
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
import SwiftUI | |
import PlaygroundSupport | |
// https://www.hackingwithswift.com/quick-start/swiftui/how-to-synchronize-animations-from-one-view-to-another-with-matchedgeometryeffect | |
struct AdaptiveStack<Content: View>: View { | |
var content: () -> Content | |
@Binding var vertical: Bool | |
init(vertical: Binding<Bool>, @ViewBuilder content: @escaping () -> Content) { | |
_vertical = vertical | |
self.content = content | |
} | |
var body: some View { | |
if vertical { | |
VStack { | |
content() | |
} | |
} else { | |
HStack { | |
content() | |
} | |
} | |
} | |
} | |
struct ContentView: View { | |
@State var vertical = true | |
@Namespace private var animation | |
var body: some View { | |
VStack { | |
Text("Other") | |
AdaptiveStack(vertical: $vertical) { | |
Text("Top").matchedGeometryEffect(id: "Top", in: animation) | |
Text("Bottom").matchedGeometryEffect(id: "Bottom", in: animation) | |
} | |
Button("vert: \(vertical.description)") { | |
withAnimation(.linear(duration: 0.2)) { | |
vertical.toggle() | |
} | |
} | |
} | |
} | |
} | |
PlaygroundPage.current.setLiveView(ContentView().frame(width: 500.0, height: 500.0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment