2

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.

1 Answer 1

4

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 !!
Sign up to request clarification or add additional context in comments.

1 Comment

I don't understand why it works like that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.