Animate a variable in swiftui

hi

Is there a way to animate a variable . for example:

i have two rectangles . both sizes are controlled by a variable . I have a slider which changes the value of the variable .

I want to animate the rectangles but I don’t want to put animation modifiers to the rectangles . I would like to put it at the slider . So the slider animates and the variable too .

is this possible ? I tried it but got no result …

then you should trigger an animate or transform method when slider value has changed

Use that slider to change the variable value which in turn changes the rectangle appearance. For example lets say that the width and height of the rectangle are tied to a State variable:

Is this what you are trying to achieve?

struct ContentView: View {
    @State private var rectSize: CGFloat = 0.5
    
    var body: some View {
        ZStack {
            VStack {
                Rectangle()
                    .fill(Color.red)
                    .frame(width: rectSize * 200, height: rectSize * 200)
                Rectangle()
                    .fill(Color.blue)
                    .frame(width: rectSize * 200, height: rectSize * 200)
            }
            VStack {
                Spacer()
                Slider(value: $rectSize)
                
            }
        }
    }
}
1 Like

hi

and now I would like to animate the slider by itself . like going left and right in like 5 seconds . and changing the value and changing the rectangles

to animate the rectangles I would have to give each an .animation modifier . In this example it’s not much work but in an other project I have much more objects .
-MJ

You mean you want the slider to move by itself from the smallest value to the largest over a 5 second period which in turn changes the size of the rectangles?

yeah something like that , then I only have to add 1 animation modifier instead of many .

maybe something like :

Slider(value: $rectSize)
.animation(Animation.spring().repeatForever(autoreverses: true) )

of course the slider is not most important the variable is .

this is the project im working on :
an experiment with the zIndex of views . A lot of modifiers to animate .

http://mj.pruts.nl/dice/dice.txt

best viewed on an iPhone 11 sized screen…

zindex

like this

1 Like

ha I got something working …

var body: some View {
ZStack {
VStack {
Rectangle()
.fill(Color.red)
.frame(width: rectSize * 200, height: rectSize * 200)
Rectangle()
.fill(Color.blue)
.frame(width: (1-rectSize) * 200, height: (1-rectSize) * 200)
}.onAppear {
withAnimation(Animation.easeInOut(duration: 5).repeatForever(autoreverses: true)) {
self.rectSize = 1.0}
}

      VStack {
            Spacer()
            Slider(value: $rectSize)
            
            
        }
    }
}