rayaantaneja
rayaantaneja

Reputation: 1748

Why isn't this simple opacity animation working in SwiftUI?

I was trying to make a simple fade in fade out animation for a text but when I try to do it this way it doesn't work. Theres no smooth increase and decrease in opacity it just jumps to full and no opacity.

struct Test: View {
    @State var showing = false
    
    var body: some View {
        VStack {
            Button("Toggle") {
                self.showing.toggle()
            }
            
            if showing {
                Text("Hello")
                    .transition(.opacity)
                    .animation(.easeInOut)
            }
        }
    }
}

Does anyone know why this doesn't work as intended? I was expecting this to have a smooth fade in fade out transition when the Text was inserted and removed from the View Hierarchy.

Upvotes: 2

Views: 1832

Answers (1)

Asperi
Asperi

Reputation: 257729

There is no-one left to animate when showing is false. Instead use the following:

VStack {
    if showing {
        Text("Hello")
            .transition(.opacity)
    }
}.animation(.easeInOut)   // << here !!

Upvotes: 4

Related Questions