简体   繁体   中英

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

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))
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM