Search code examples
swiftswiftuiswiftui-animationswiftui-transition

SwiftUI Animation: How do I customize the transition animation (fade out THEN fade in)


This code would produce an animation that crossfades the values whenever I change self.myTextString:

// In some View's body method
Text(self.myTextString)
.transition(.opacity)
.animation(.easeInOut(duration: 0.6), value: self.myTextString)

What I'd like it to do is fade out the old value completely THEN begin fading in the newValue.

It didn't seem clear / obvious how to do this. Do I need to make a custom Transition? Any examples anywhere of somebody doing such a thing? (Let the outgoing do something and complete, then the incoming can start animating?)


Solution

  • If you know the delay, you can make an asymmetric transition and delay on of them to appear as you like:

    Text(self.myTextString)
        .transition(
            .asymmetric(
                insertion: .opacity.animation(.easeIn.delay(0.6)),
                removal: .opacity.animation(.easeOut)
            )
        )
        .id(myTextString)
        .animation(.default, value: self.myTextString)
    

    Demo

    Note transition works for new objects (new identities)

    otherwise, you need to break the transition into two separated state (like a loading state and a complete state) and trigger for each separately