Skip to content

Instantly share code, notes, and snippets.

@bitwit
Last active January 31, 2021 18:55
Show Gist options
  • Save bitwit/af3e12304a88f18ccee566540cf25cb0 to your computer and use it in GitHub Desktop.
Save bitwit/af3e12304a88f18ccee566540cf25cb0 to your computer and use it in GitHub Desktop.
animation stack change after size class changes
import SwiftUI
final class SizeClassNotifier: ObservableObject {
@Published var currentSizeClass: UserInterfaceSizeClass =
.compact
func updateSizeClass(sizeClass: UserInterfaceSizeClass?) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.currentSizeClass = sizeClass ?? .compact
}
}
}
struct AdaptiveStackView: View {
@Environment(\.verticalSizeClass) var sizeClass
@ObservedObject var sizeClassNotifier: SizeClassNotifier = .init()
@Namespace var animation
var body: some View {
VStack {
if sizeClassNotifier.currentSizeClass == .compact {
VStack {
Text("Hello")
.matchedGeometryEffect(id: "hello", in: animation)
Text("World")
.matchedGeometryEffect(id: "world", in: animation)
}
} else {
HStack {
Text("Hello")
.matchedGeometryEffect(id: "hello", in: animation)
Text("World")
.matchedGeometryEffect(id: "world", in: animation)
}
}
}
.animation(.linear)
.onChange(of: sizeClass ?? .compact, perform: { value in
self.sizeClassNotifier.updateSizeClass(sizeClass: value)
})
}
}
struct AdaptiveStackView_Previews: PreviewProvider {
static var previews: some View {
AdaptiveStackView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment