SwiftUI - 矩形的动画高度从 0 到高度

SwiftUI - Animate height of rectangle from 0 to height

我正在尝试将 RoundedRectangle() 的高度从 0 设置为新高度,我希望它在我的设备摇晃时从当前位置向上增长。按照目前的情况,我有一个 onShake 函数,我想激活矩形的增长。

struct View1: View {
    
    var body: some View {
        ZStack {
            Color.white
                .edgesIgnoringSafeArea(.all)
            Text("Hola")
                .foregroundColor(.black)
                .font(.headline)
            RoundedRectangle(cornerRadius: 5)
                .frame(width: 100, height: 0, alignment: .center)
                .foregroundColor(Color("RedColour"))
                .onShake {
                    withAnimation {
                        self.frame(width: 100, height: 100)
                    }
                }
        }
    }
}

你可能会说我是 SwiftUI 的新手,对动画的工作原理知之甚少。随意为它烤我,但我也希望在我的设备摇晃时尝试向上增长这个矩形。

大爱!

你可以试试这个。但是由于您提供的信息没有包括您想要如何使用它,这可能是不完整的。

struct View1: View {
    @State private var height: CGFloat = 0 // add this to modify 
                                           // the height of the Rounded Rectangle
    let targetHeight: CGFloat = 100 // targetHeight var to syncronise with the VStack
    var body: some View {
        ZStack {
            Color.white
                .edgesIgnoringSafeArea(.all)
            Text("Hola")
                .foregroundColor(.black)
                .font(.headline)
                .background{
                    VStack{
                        Spacer(minLength: 0)
                        RoundedRectangle(cornerRadius: 5)
                            .frame(width: 100, height: height)
                            .foregroundColor(.red)
                            .onShake {
                                withAnimation(.linear(duration: 5)) {
                                    height = targetHeight
                                }
                            }
                    }.frame(height: targetHeight) // VStack with fixed height
                                                  //to animate from bottom up
                }
        }
    }
}