SwiftUI SwiftUI Views and Layout 2 — Questions and Answers
Question 1: Which container view in SwiftUI creates a scrollable list of items?
- ForEach
- ScrollView (Correct answer)
- LazyVStack
- Group
Correct answer: ScrollView
ScrollView provides a scrolling container for its child content.
Question 2: What does the `.padding()` modifier do when called with no arguments?
- Adds 0 padding
- Adds system-default padding on all sides (Correct answer)
- Adds padding only on leading and trailing
- Removes existing padding
Correct answer: Adds system-default padding on all sides
Calling `.padding()` with no arguments applies the system default padding amount on all four sides.
Question 3: Which view type should you use for a horizontally scrollable row of cards?
- VStack inside ScrollView
- ScrollView(.horizontal) with HStack (Correct answer)
- LazyHGrid
- TabView
Correct answer: ScrollView(.horizontal) with HStack
A horizontal ScrollView containing an HStack is the standard pattern for horizontally scrollable content.
Question 4: What is the role of `GeometryReader` in SwiftUI?
- It reads shape geometry for animations
- It provides the parent view's size and coordinate space (Correct answer)
- It measures text line counts
- It handles touch geometry
Correct answer: It provides the parent view's size and coordinate space
GeometryReader exposes a GeometryProxy that gives the view access to its parent container's size and coordinate space.
Question 5: Which alignment option centers content both horizontally and vertically in a ZStack?
- .leading
- .center (Correct answer)
- .topLeading
- .bottomTrailing
Correct answer: .center
ZStack's default alignment is `.center`, which centers children both horizontally and vertically.
Question 6: What does `LazyVStack` do differently compared to `VStack`?
- It supports horizontal scrolling
- It only renders views as they come on screen (Correct answer)
- It caches views off-screen
- It supports sections automatically
Correct answer: It only renders views as they come on screen
LazyVStack defers creating views until they are about to be visible, improving performance for large datasets.
Which container view in SwiftUI creates a scrollable list of items?