Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Animate resize of a view frame

How do you animate the size of a view, such that the view may grow or shrink using the frame height? I need to transition between two known dimensions.

like image 394
Yarm Avatar asked Jan 13 '20 13:01

Yarm


2 Answers

I don't know exactly what you need but here is a very basic example with a Rectangle that gets scaled when you tap the Button:

struct ContentView: View {

    @State var animate = false

    var body: some View {
        VStack {
            Button(action: {
                withAnimation {
                    self.animate.toggle()
                }
            }, label: {
                Text("Animate")
            })
            Rectangle()
                .foregroundColor(.blue)
                .frame(width: self.animate ? 100 : 150, height: self.animate ? 60 : 90)
        }
    }
}

Please add some code to your next question or edit the question so people can provide a more specific answer.

like image 194
krjw Avatar answered Nov 12 '22 03:11

krjw


Since withAnimation { } animate everything related to State changes inside the closure , we can use .animation() modifier to animate specific one.

struct ContentView: View {

    @State var animate = false

    var body: some View {
        VStack {
            Button(action: {
                    self.animate.toggle()
            }, label: {
                Text("Animate")
            })
            Rectangle()
                .foregroundColor(.blue)
                .frame(width: animate ? 100 : 150, height: animate ? 60 : 90)
                .animation(.default) //you can change the animation you need 
            }
        }
    }
like image 27
Yodagama Avatar answered Nov 12 '22 02:11

Yodagama