Bird
0
0

What will be the visible effect of this SwiftUI code?

medium📝 Predict Output Q4 of 15
iOS Swift - Animations
What will be the visible effect of this SwiftUI code?
struct ContentView: View {
  @State private var showText = false
  var body: some View {
    VStack {
      if showText {
        Text("Welcome")
          .transition(.opacity)
      }
      Button("Toggle") {
        withAnimation {
          showText.toggle()
        }
      }
    }
  }
}
AThe text slides in from the left when toggled
BThe text fades in and out smoothly when toggled
CThe text appears and disappears instantly without animation
DThe button animates but the text does not change
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the transition

    The .transition(.opacity) modifier animates the text's opacity when it appears or disappears.
  2. Step 2: Understand the animation trigger

    The withAnimation block ensures the toggle of showText triggers the transition animation.
  3. Final Answer:

    The text fades in and out smoothly when toggled -> Option B
  4. Quick Check:

    Opacity transition with withAnimation triggers fade effect [OK]
Quick Trick: Use .transition(.opacity) with withAnimation for fade effects [OK]
Common Mistakes:
  • Expecting slide animation instead of opacity fade
  • Omitting withAnimation so transition is not animated

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes