Home > Net >  SwiftUI - Animate height of rectangle from 0 to height
SwiftUI - Animate height of rectangle from 0 to height

Time:04-12

I am attempting to animate the height of a RoundedRectangle() from 0 to its new height, I would like it to grow from its current position upwards when my device shakes. As it currently stands, I have a onShake function which I want to activate the growing of the rectangle.

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)
                    }
                }
        }
    }
}

As you can probably tell I am very new to SwiftUI and have very limited knowledge of how animations work. Feel free to grill me for it, but I would also love some help with attempting to grow this rectangle upwards when my device shakes.

Much love!

CodePudding user response:

You could try this. But as the information you provided do not include how you want to use this, this might be incomplete.

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
                }
        }
    }
}
  • Related