Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate hideable views with SwiftUI?

I'm trying out SwiftUI, and while I've found many of its features very elegant, I've had trouble with animations and transitions. Currently, I have something like

if shouldShowText { Text(str).animation(.default).transition(AnyTransition.opacity.animation(.easeInOut)) }

This label does transition properly, but when it's supposed to move (when another view above is hidden, for instance) it does not animate as I would have expected, but rather jumps into place. I've noticed that wrapping everything in an HStack works, but I don't see why that's necessary, and I was hoping that there is a better solution out there.

Thanks

like image 781
Etan Ossip Avatar asked Sep 12 '25 10:09

Etan Ossip


1 Answers

If I correctly understood and reconstructed your scenario you need to use explicit withAnimation (depending on the needs either for "above view" or for both) as shown below

struct SimpleTest: View {

    @State var shouldShowText = false
    @State var shouldShowAbove = true
    var body: some View {
        VStack {
            HStack
            {
                Button("ShowTested") { withAnimation { self.shouldShowText.toggle() } }
                Button("HideAbove") { withAnimation { self.shouldShowAbove.toggle() } }
            }
            Divider()
            if shouldShowAbove {
                Text("Just some above text").padding()
            }
            if shouldShowText {
                Text("Tested Text").animation(.default).transition(AnyTransition.opacity.animation(.easeInOut))
            }
        }
    }
}
like image 123
Asperi Avatar answered Sep 14 '25 03:09

Asperi