Animating the hiding/showing of a view with a Toggle

Viewed 298

Here is my code

@State private var show = false

...

Form {
    Toggle(isOn: $show, label: { Text("Show the text?") })
    if show {
        Text("Hello World")
    }
}

With a button that would have the action self.show.toggle() I can animate the slide with a withAnimation{} statement but I'm not sure how to do it with a toggle.

2 Answers

This could give you better Animation:

  Form
  {
    
    Toggle(isOn: $show, label: { Text("Show the text?") })
    
    Group
    {
        if show { Text("Hello World") } else { EmptyView() }
    }
 }
   .animation(.easeOut)

You can add the .animation(.easeOut) modifier to your Text view like so -

@State private var show = false

...

Form {
    Toggle(isOn: $show, label: { Text("Show the text?") })
    if show {
        Text("Hello World")
           .animation(.easeOut)
    }
}

By adding this modifier, any changes applied to the view will be animated.

From Apple's basic animation tutorial - When you use the animation(_:) modifier on a view, SwiftUI animates any changes to animatable properties of the view. A view’s color, opacity, rotation, size, and other properties are all animatable.

You can also animate specific part of the view, or the way you want it to appear, for example set the color to black with opacity of 0 and if show == true it sets back to 1 (fully visible)

@State private var show = false

...

Form {
    Toggle(isOn: $show, label: { Text("Show the text?") })
    if show {
        Text("Hello World")
           .foregroundColor(show ? Color.black : Color.black.opacity(0)) // if show is true than foreground color is black, if show is false than color is black with opacity 0.0 (not visible)
           .animation(.easeOut)
    }
} 
Related