Bird
0
0

You want to animate a view's opacity from 0 to 1 over 2 seconds when a button is tapped. Which code correctly uses withAnimation to achieve this?

hard📝 Application Q15 of 15
iOS Swift - Animations
You want to animate a view's opacity from 0 to 1 over 2 seconds when a button is tapped. Which code correctly uses withAnimation to achieve this?
AwithAnimation(.easeOut) { self.opacity = 1; DispatchQueue.main.asyncAfter(deadline: .now() + 2) {} }
BwithAnimation(.linear(duration: 2)) { self.isVisible = true }
CwithAnimation { self.isVisible = true; sleep(2) }
DwithAnimation(.spring()) { self.opacity = 0 }
Step-by-Step Solution
Solution:
  1. Step 1: Identify the animation type and duration

    To animate opacity over 2 seconds linearly, use .linear(duration: 2).
  2. Step 2: Check the state change inside withAnimation

    Setting isVisible = true triggers the opacity change if bound correctly.
  3. Step 3: Evaluate other options

    withAnimation { self.isVisible = true; sleep(2) } uses sleep which blocks UI; withAnimation(.easeOut) { self.opacity = 1; DispatchQueue.main.asyncAfter(deadline: .now() + 2) {} } misuses asyncAfter; withAnimation(.spring()) { self.opacity = 0 } animates opacity to 0, not 1.
  4. Final Answer:

    withAnimation(.linear(duration: 2)) { self.isVisible = true } -> Option B
  5. Quick Check:

    Use withAnimation with linear duration and state change [OK]
Quick Trick: Use withAnimation with duration and change state inside braces [OK]
Common Mistakes:
  • Using sleep inside animation block
  • Misusing asyncAfter for animation timing
  • Animating wrong property value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes