如何在 SwiftUI List 中使用自定义视图顺利展开行单元格?

How to expand a row cell smoothly with a custom view in SwiftUI List?

我正在尝试在点击手势时扩展一个行单元格(这是一个自定义视图)。 必须增加单元格高度,并在扩展区域中移动一个按钮。 但是我得到了以下跳跃的动画效果。按下的蓝色卡片应保持稳定,但它会跳来跳去。

重现这个跳跃动画的简单代码:

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, World!")
            List {
                Detail(isExpanded: false)
                Detail(isExpanded: false)
                Detail(isExpanded: false)
            }
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}



struct Detail: View {
    @State var isExpanded :Bool
    var body: some View {
        ZStack {
            ZStack {
                RoundedRectangle(cornerRadius: 8)
                .fill(Color(red: 0.0, green: 1.0, blue: 1.0, opacity: 1.0)).frame(height: 115)
                Text("Hello, World!")
            }.zIndex(3).frame(height: 115).contentShape(Rectangle()).onTapGesture {
                withAnimation {
                    self.isExpanded.toggle()
                }
            }
            Button(action: {
            }) {
                ZStack {
                    RoundedRectangle(cornerRadius: 50)
                        .fill(Color(red: 1.0, green: 0.0, blue: 1.0, opacity: 1.0)).frame(height: 70)
                        .cornerRadius(8)
                        .shadow(radius: 3)
                        Text("Test")
                }
            }.padding([.leading, .trailing], 12)
                .padding(.top, 6)
                .frame(height: 70)
                .buttonStyle(BorderlessButtonStyle())
                .offset(y: self.isExpanded ? 0 : 40)
                .disabled(!self.isExpanded)
        }.frame(height: self.isExpanded ? 120 : 200)
    }
}

对于如何解决这个问题的任何提示或提示,我深表感谢。

编辑

单击时,hello world 卡片应在单元格本身的顶部保持对齐。像这样:

只需使用动画修饰符

测试 Xcode 11.4 / iOS 13.4

ZStack {
 // .. other your code here
}
.modifier(AnimatingCellHeight(height: self.isExpanded ? 120 : 200))