Bird
0
0

Given this SwiftUI code snippet, what will happen when the button toggles isExpanded?

medium📝 Predict Output Q4 of 15
iOS Swift - Animations
Given this SwiftUI code snippet, what will happen when the button toggles isExpanded?
struct ContentView: View {
  @Namespace var ns
  @State var isExpanded = false
  var body: some View {
    VStack {
      if isExpanded {
        RoundedRectangle(cornerRadius: 25)
          .matchedGeometryEffect(id: "shape", in: ns)
          .frame(width: 300, height: 300)
      } else {
        RoundedRectangle(cornerRadius: 25)
          .matchedGeometryEffect(id: "shape", in: ns)
          .frame(width: 100, height: 100)
      }
      Button("Toggle") { isExpanded.toggle() }
    }
  }
}
AThe app crashes due to missing namespace.
BThe rectangle instantly changes size without animation.
CThe rectangle smoothly animates between small and large sizes.
DThe rectangle disappears when toggled.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze matchedGeometryEffect usage

    Both views share the same id and namespace, enabling smooth geometry animation.
  2. Step 2: Understand toggle effect

    Toggling isExpanded switches between two frames, animating size change.
  3. Final Answer:

    The rectangle smoothly animates between small and large sizes. -> Option C
  4. Quick Check:

    matchedGeometryEffect animates size changes smoothly [OK]
Quick Trick: matchedGeometryEffect animates size and position changes [OK]
Common Mistakes:
  • Expecting instant size change without animation
  • Assuming app crashes without namespace (namespace is declared)
  • Thinking view disappears on toggle

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes