Home > Software engineering >  SwiftUI transition animation is only working when I use a deprecated API
SwiftUI transition animation is only working when I use a deprecated API

Time:12-03

I'm trying to get a very simple transition animation to work in SwiftUI. The transition works perfectly when I include the following:

.animation(.linear)

But when I do that I get the following warning message:

'animation' was deprecated in iOS 15.0: Use withAnimation or animation(_:value:) instead

I am already using withAnimation in my code (see below).

struct ShowAnimationProblemView: View {
    @State var showingSubView = false
    
    var body: some View {
        VStack {
            Text("Animation Transition Problem").padding()
            Button("Show subView") {
                withAnimation {
                    showingSubView.toggle()
                }
            }.padding()
            if showingSubView {
                VStack {
                    Text("This is")
                    Text("the")
                    Text("subView")
                }
                .padding(50)
                .border(.red)
                .transition(.slide)
            }
            Spacer()
        }
        .animation(.linear)
    }
}

A picture of the view

The code, as shown above works perfectly, but shows the deprecation warning. When you tap the button, the subView slides in from the left. When you tap it again, the subView slides out to the right.

If I comment out the .animation(.linear) statement, then the first time I tap the button, the subView instantly appears with no animation. Then if I tap it again, it nicely slides out to the right.

How can I get this simple transition to work correctly without using the deprecated API?

CodePudding user response:

Replace the deprecated version:

.animation(.linear)

with this:

.animation(.linear, value: showingSubView)

Note: The animation works without the withAnimation { }.

  • Related