我正在尝试创建一个视图,其中显示具有不同订阅的卡片,并且当您切换时,它们会展开以显示详细信息。我希望一张卡片的动画能够平滑地影响其他卡片,无缝地移动它们。
这是我到目前为止所取得的结果
这就是我的代码
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()
}
正如您所看到的,动画很紧张并且看起来不太好。我尝试使用matchedGeometryEffect,但它似乎没有改变任何东西 - 我可能做错了。有谁知道如何正确执行此操作?
我不会尝试用于
.matchedGeometryEffect
此目的。相反,您只需更改绑定的使用方式即可使动画产生更广泛的影响。将切换开关更改为:
然后注释掉
.matchedGeometryEffect
、.animation
修饰符和多余的命名空间。像这样: