Thinking animation requires .animation() modifier here
Assuming instant appearance without animation
4. Identify the error in this SwiftUI code snippet that tries to animate a color change:
@State private var isRed = true
var body: some View {
Rectangle()
.fill(isRed ? Color.red : Color.blue)
.onTapGesture {
isRed.toggle()
}
.animation(.easeInOut)
}
medium
A. The .animation modifier is deprecated and should be replaced with withAnimation.
B. The state variable isRed should not be toggled inside onTapGesture.
C. The Rectangle view cannot change fill color dynamically.
D. The .fill modifier must be outside the Rectangle view.
Solution
Step 1: Understand .animation modifier usage
The .animation modifier on a view is deprecated and may not animate state changes reliably.
Step 2: Use withAnimation for state changes
Wrapping the state toggle inside withAnimation ensures the color change animates properly.
Final Answer:
The .animation modifier is deprecated and should be replaced with withAnimation. -> Option A
Quick Check:
Use withAnimation, not .animation modifier [OK]
Hint: Use withAnimation to animate state changes, not .animation modifier [OK]
Common Mistakes:
Using .animation modifier on views instead of withAnimation
Thinking onTapGesture cannot toggle state
Misplacing .fill modifier
5. You want to animate a button's scale when pressed and return to normal size when released. Which approach correctly combines state and animation in SwiftUI?
hard
A. Use a Timer to change scale repeatedly for animation effect.
B. Use a @GestureState to track pressing and apply .scaleEffect with .animation inside the gesture.
C. Toggle a @State variable on tap and use .animation on the button without gestures.
D. Apply .animation modifier directly on the button without state changes.
Solution
Step 1: Understand gesture-driven animations
Using @GestureState tracks the pressing state smoothly during the gesture lifecycle.
Step 2: Apply scaleEffect with animation inside gesture
Applying .scaleEffect based on gesture state and animating it creates a responsive press effect.
Step 3: Evaluate other options
Options A, B, and D either lack gesture responsiveness or misuse animation techniques.
Final Answer:
Use a @GestureState to track pressing and apply .scaleEffect with .animation inside the gesture. -> Option B