Home > Software engineering >  How to get different components to have different animations?
How to get different components to have different animations?

Time:07-15

I have two simple ui components a Rectangle and an Image. I just want a slide animation for Rectangle and scale animation for Image.

However, I got a default value animation for both of these. Is there a problem in my code? I don't have any error. I'm using beta SF Symbols tho. Could this be the problem?

import SwiftUI

struct ContentView: View {
@State var animate: Bool = false
    var body: some View {
    VStack(alignment: .center) {
        HStack() {
            if animate {
                
                ZStack() {
                    Rectangle()
                        .frame(height: 50)
                        .transition(.slide)
                    Image(systemName: "figure.mixed.cardio")
                        .foregroundColor(.white)
                        .transition(.scale)
                }
                
            }
        }
        Button("animate") {
            withAnimation {
                animate.toggle()
            }
        }
    }
  }
} 

CodePudding user response:

Transition works when specific view appeared, but in your code ZStack loads views and then appears as a whole.

Here is a fix:

    HStack() {
        ZStack() {
            if animate {   // << here !!
            
                Rectangle()
                    .frame(height: 50)
                    .transition(.slide)
                Image(systemName: "figure.mixed.cardio")
                    .foregroundColor(.white)
                    .transition(.scale)
            }
            
        }
    }

CodePudding user response:

The problem here is neither your SF Symbols or Compiling Error. Animation is a bit tricky especially if you want different animations for different views inside the same stack.

To achieve your goal, you need to wrap each sub view inside an independent stack, then they will have their own unique animation.

Try this code:

import SwiftUI

struct TestView: View {

@State var animate: Bool = false

var body: some View {
    VStack(alignment: .center) {
        HStack() {
            ZStack() {
                //added
                if animate {
                    ZStack {
                        Rectangle()
                            .frame(height: 50)
                         
                    }   .transition(.slide)
                }
                //added
                if animate {
                    ZStack {
                        Image(systemName: "figure.mixed.cardio")
                            .foregroundColor(.white)
                            
                    }.transition(.scale)
                }
            }
        }
        Button("animate") {
            withAnimation {
                animate.toggle()
            }
        }
    }
  }
}
  • Related