Hey, I'm trying to create a view where cards with different subscriptions are displayed, and when you toggle, they expand to show details. I want the animation of one card to smoothly affect others, seamlessly shifting them.
Here is the result I have achieved so far
And that's my code
import SwiftUI
struct ContentView: View {
@State private var toogle1: Bool = false
@State private var toogle2: Bool = false
var body: some View {
VStack(spacing: 0) {
ScrollView {
VStack {
subscriptionCurrentYearView()
subscriptionPreviousYearView()
}
.padding(16)
}
}
}
@ViewBuilder
func subscriptionCurrentYearView() -> some View {
SubscriptionView(toggleOn: $toogle1)
}
@ViewBuilder
func subscriptionPreviousYearView() -> some View {
SubscriptionView(toggleOn: $toogle2)
}
}
struct SubscriptionView: View {
@Namespace private var animation
@Binding var toggleOn: Bool
var body: some View {
VStack {
HStack {
Text("I want to subscribe this product from the current year")
.foregroundColor(.secondary)
.frame(width: 250, alignment: .leading)
Toggle("", isOn: $toggleOn)
.frame(width: 50)
}
.matchedGeometryEffect(id: "Header", in: animation)
.padding()
if toggleOn {
VStack(alignment: .leading) {
Text("Estimated current balance")
TextField("", text: .constant("$ 0.00"))
.font(.title)
Text("Your whole amount must be transferred for the current tax year")
}
.matchedGeometryEffect(id: "Content", in: animation)
.foregroundColor(.secondary)
.padding()
}
}
.frame(maxHeight: .infinity)
.padding()
.background(Color(uiColor: UIColor.lightGray))
.clipShape(RoundedRectangle(cornerRadius: 20))
.animation(.linear, value: toggleOn)
}
}
#Preview {
ContentView()
}
As you can see, the animation is jittery and doesn't look good. I tried using matchedGeometryEffect, but it doesn't seem to change anything - I'm probably doing it wrong. Does anyone know how to do this correctly?
OK thanks for benzy-neez on stack overflow I found solution here is full code if someone is curious.
struct SubscriptionView: View {
// @Namespace private var animation
@Binding var toggleOn: Bool
var body: some View {
VStack {
HStack {
Text("I want to subscribe this product from the current year")
.foregroundColor(.secondary)
.frame(width: 250, alignment: .leading)
Toggle("", isOn: $toggleOn.animation())
.frame(width: 50)
}
// .matchedGeometryEffect(id: "Header", in: animation)
.padding()
if toggleOn {
VStack(alignment: .leading) {
Text("Estimated current balance")
TextField("", text: .constant("$ 0.00"))
.font(.title)
Text("Your whole amount must be transferred for the current tax year")
}
// .matchedGeometryEffect(id: "Content", in: animation)
.foregroundColor(.secondary)
.padding()
}
}
.frame(maxHeight: .infinity)
.padding()
.background(Color(uiColor: UIColor.lightGray))
.clipShape(RoundedRectangle(cornerRadius: 20))
// .animation(.linear, value: toggleOn)
}
}