Search code examples
swiftanimationswiftuitransition

Why is my view not transitioning when first appeared on screen in swiftUI


I want a simple view to scale from 0 to 1 when the app first loads. How ever its not happening.Look at my code here:

struct ContentView: View {
    
    @State private var isLoadng = false
    
    var body: some View {
        
        ZStack {
            if isLoadng {
                Color.red
                    .cornerRadius(20)
                    .frame(width: 150, height: 200)
                    .transition(.scale)
               
            }
            
            
        }
        
        .onAppear {
            withAnimation(.easeInOut(duration: 2)) {
                self.isLoadng = true
            }
        }
    }
}

The view just popping up without any transition


Solution

  • Here is modified part. Tested with Xcode 12

    var body: some View {
        ZStack {
            if isLoadng {
                Color.red
                    .cornerRadius(20)
                    .frame(width: 150, height: 200)
                    .transition(.scale)
            }
        }
        .animation(.easeInOut(duration: 2))
        .onAppear {
            self.isLoadng = true
        }
    }