struct ContentView: View {
@State private var animationAmount = 1.0
var body: some View {
VStack
{
Stepper("Scale amount", value: $animationAmount.animation(.linear), in: 1...10)
Spacer()
Button("Tap Me")
{
animationAmount = 1
}
.padding(50)
.background(.red)
.foregroundColor(.white)
.clipShape(Circle())
.scaleEffect(animationAmount)
}
}
}
So I have a tiny question, here I made a Stepper view with value being some way two binding of a variable and then I called the .animation method on that binding which from what I understood, if any changes happen to that binding they simply get animated. My question is, is it specifically only changes that relate to the binding value that get animated? Or if some other changes happen to this view but coincidentally they happened a bit before the binding changed would those changes get animated too?
And another super super tiny question, why is it exactly that I can't put an if statement in this VStack that will increment animationAmount? like
if animationAmount > 1.0
{
animationAmount = 0.25
}
Just says that () doesn't conform to View.
CodePudding user response:
By definition, .animation(_:value:)
:
Applies the given animation to this view when the specified value changes.
So yes, the animation applies only when the value you passed changes, see more: .animation(_:value:)
To answer your second question,VStack, HStack,... & body
are ViewBuilders
. Meaning they require you to pass in a View
, whereas animationAmount = 0.25
is of type Void
!= View
. So what you should do is use .onChange
:
.onChange(of: animationAmount) { newValue in
if animationAmount > 1.0 {
animationAmount = 0.25
}
}
CodePudding user response:
First question: .animation works by animating a specific component whenever the value of this component changes.
eg: foregroundColor(color.animation) meaning that if the value of variable color changes, animation will happen BUT only to this foregroundColor component, unless you give another component color.animation too. Any other changes in view/variable beside this variable color will not apply animation to this foregroundColor. Any change even a very small change of variable color will animate the foregroundColor.
There is another different type of animation called withAnimation.
eg: withAnimation { isViewed = true }, now all the views or modifiers that relate to this variable isViewed will be animated.
Second question: To make it easy to understand, you simply can’t make any calculation/logic process inside a SwiftUI View Bracket. An ifelse{} statement inside a VStack or var body expects Views, so you can’t make any calculation there because it is not a view. Any code inside this ifelse bracket {. . .} shall be views only.
However, an ifelse{} statement inside a Button Action or onTapGesture is an opposite story. You can make any calculation/logic process there except displaying views. To understand formally about these concepts you should explore more about the basic of SwiftUI.