Bird
Raised Fist0
iOS Swiftmobile~20 mins

LazyVStack and LazyHStack in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Lazy Stacks Demo
This screen shows a vertical list and a horizontal list using LazyVStack and LazyHStack. It helps to display many items efficiently by loading views only when needed.
Target UI
-------------------------
| Lazy Stacks Demo       |
|-----------------------|
| Vertical List:         |
| 1. Item 1             |
| 2. Item 2             |
| 3. Item 3             |
| ...                   |
|                       |
| Horizontal List:       |
| [Item 1] [Item 2] ... |
-------------------------
Use LazyVStack inside a ScrollView for vertical list of 50 items labeled 'Item 1' to 'Item 50'.
Use LazyHStack inside a horizontal ScrollView for horizontal list of 20 items labeled 'Item 1' to 'Item 20'.
Each item should be a rounded rectangle with a light gray background and the item label centered.
Add padding around stacks for spacing.
The screen should have a title 'Lazy Stacks Demo' at the top.
Starter Code
iOS Swift
import SwiftUI

struct LazyStacksDemoView: View {
    var body: some View {
        VStack {
            Text("Lazy Stacks Demo")
                .font(.title)
                .padding()

            ScrollView {
                // TODO: Add LazyVStack here
            }

            ScrollView(.horizontal) {
                // TODO: Add LazyHStack here
            }
        }
        .padding()
    }
}

struct LazyStacksDemoView_Previews: PreviewProvider {
    static var previews: some View {
        LazyStacksDemoView()
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
iOS Swift
import SwiftUI

struct LazyStacksDemoView: View {
    var body: some View {
        VStack {
            Text("Lazy Stacks Demo")
                .font(.title)
                .padding()

            ScrollView {
                LazyVStack(spacing: 10) {
                    ForEach(1...50, id: \.self) { i in
                        Text("Item \(i)")
                            .multilineTextAlignment(.center)
                            .frame(maxWidth: .infinity)
                            .padding()
                            .background(Color.gray.opacity(0.2))
                            .cornerRadius(8)
                    }
                }
                .padding()
            }

            ScrollView(.horizontal) {
                LazyHStack(spacing: 10) {
                    ForEach(1...20, id: \.self) { i in
                        Text("Item \(i)")
                            .multilineTextAlignment(.center)
                            .frame(width: 80, height: 50)
                            .padding()
                            .background(Color.gray.opacity(0.2))
                            .cornerRadius(8)
                    }
                }
                .padding()
            }
        }
        .padding()
    }
}

struct LazyStacksDemoView_Previews: PreviewProvider {
    static var previews: some View {
        LazyStacksDemoView()
    }
}

We use LazyVStack inside a vertical ScrollView to efficiently show 50 items vertically. Each item is a Text with padding and a light gray rounded rectangle background for a clean look.

Similarly, LazyHStack inside a horizontal ScrollView shows 20 items horizontally. Each item has fixed width and height to keep consistent size and uses the same styling.

Padding and spacing between items improve readability and touch targets. The title is styled with a larger font and padding at the top.

Final Result
Completed Screen
-------------------------
| Lazy Stacks Demo       |
|-----------------------|
| Vertical List:         |
| [Item 1]              |
| [Item 2]              |
| [Item 3]              |
| ...                   |
|                       |
| Horizontal List:       |
| [Item 1] [Item 2] ... |
-------------------------
User can scroll vertically through the 50 items in the LazyVStack.
User can scroll horizontally through the 20 items in the LazyHStack.
Items load smoothly as user scrolls because of lazy loading.
Stretch Goal
Add a toggle button to switch between light and dark mode for the screen.
💡 Hint
Use @Environment(\.colorScheme) and a @State variable to toggle colorScheme, then apply background and text colors accordingly.

Practice

(1/5)
1. What is the main purpose of using LazyVStack or LazyHStack in SwiftUI?
easy
A. To add animations to views automatically
B. To create stacks that load all views immediately
C. To create stacks that load views only when they appear on screen
D. To disable scrolling in a list

Solution

  1. Step 1: Understand Lazy Stacks behavior

    LazyVStack and LazyHStack create views only when they are about to appear on screen, saving memory.
  2. Step 2: Compare with normal stacks

    Normal VStack or HStack create all views immediately, which can be slow for large lists.
  3. Final Answer:

    To create stacks that load views only when they appear on screen -> Option C
  4. Quick Check:

    Lazy stacks load views lazily = D [OK]
Hint: Lazy stacks create views only when visible on screen [OK]
Common Mistakes:
  • Thinking lazy stacks load all views at once
  • Confusing lazy stacks with animation features
  • Assuming lazy stacks disable scrolling
2. Which of the following is the correct syntax to create a vertical lazy stack with 5 Text views labeled "Item 1" to "Item 5"?
easy
A. LazyVStack(1...5) { i in Text("Item \(i)") }
B. LazyVStack { ForEach(1...5, id: \.self) { i in Text("Item \(i)") } }
C. LazyVStack { ForEach(0..<5) { i in Text("Item \(i + 1)") } }
D. LazyVStack { ForEach(1...5) { i in Text("Item \(i)") } }

Solution

  1. Step 1: Check ForEach usage with range and id

    ForEach needs an identifiable range; using 1...5 with id: \.self is correct.
  2. Step 2: Verify Text label inside loop

    Text("Item \(i)") correctly shows labels from Item 1 to Item 5.
  3. Final Answer:

    LazyVStack with ForEach(1...5, id: \.self) and Text("Item \(i)") -> Option B
  4. Quick Check:

    Correct ForEach syntax with id = A [OK]
Hint: Use ForEach with id: \.self for ranges in Lazy stacks [OK]
Common Mistakes:
  • Omitting id parameter in ForEach with ranges
  • Using incorrect range syntax
  • Forgetting to add 1 when using 0..<5 for labels
3. What will be the visible output when running this SwiftUI code inside a ScrollView?
ScrollView {
  LazyHStack {
    ForEach(1...3, id: \.self) { i in
      Text("Number \(i)")
    }
  }
}
medium
A. A vertical column showing: Number 1 Number 2 Number 3
B. No output because LazyHStack needs LazyVStack
C. An error because LazyHStack cannot be inside ScrollView
D. A horizontal row showing: Number 1 Number 2 Number 3

Solution

  1. Step 1: Understand ScrollView with LazyHStack

    ScrollView by default scrolls vertically, but LazyHStack arranges views horizontally.
  2. Step 2: Check ForEach output

    ForEach creates Text views labeled Number 1, Number 2, Number 3 in a horizontal line.
  3. Final Answer:

    A horizontal row showing: Number 1 Number 2 Number 3 -> Option D
  4. Quick Check:

    LazyHStack arranges horizontally = B [OK]
Hint: LazyHStack arranges views horizontally inside ScrollView [OK]
Common Mistakes:
  • Assuming LazyHStack arranges views vertically
  • Thinking LazyHStack cannot be inside ScrollView
  • Confusing LazyVStack and LazyHStack behavior
4. Identify the error in this SwiftUI code snippet:
ScrollView {
  LazyVStack {
    ForEach(0..<5) { i in
      Text("Item \(i)")
    }
  }
}
medium
A. Missing id parameter in ForEach causes a compile error
B. LazyVStack cannot be inside ScrollView
C. Text view syntax is incorrect
D. Range 0..<5 is invalid in ForEach

Solution

  1. Step 1: Check ForEach usage with range

    ForEach with range 0..<5 requires an id parameter to identify each element uniquely.
  2. Step 2: Confirm other parts are correct

    LazyVStack inside ScrollView is valid; Text syntax is correct; range 0..<5 is valid.
  3. Final Answer:

    Missing id parameter in ForEach causes a compile error -> Option A
  4. Quick Check:

    ForEach with range needs id = A [OK]
Hint: Always add id: \.self for ForEach with ranges [OK]
Common Mistakes:
  • Forgetting id parameter in ForEach with ranges
  • Thinking LazyVStack can't be inside ScrollView
  • Misreading range syntax as invalid
5. You want to display a horizontally scrolling list of 1000 images efficiently. Which approach is best to keep your app fast and memory-friendly?
hard
A. Use ScrollView with LazyHStack and load images lazily inside ForEach
B. Use ScrollView with HStack and load all 1000 images immediately
C. Use VStack with LazyVStack inside ScrollView
D. Use List with VStack and load images eagerly

Solution

  1. Step 1: Understand lazy loading for large lists

    LazyHStack inside ScrollView creates views only when needed, saving memory for large lists.
  2. Step 2: Compare with eager loading

    HStack or VStack loads all views immediately, which is slow and memory-heavy for 1000 images.
  3. Step 3: Confirm horizontal scrolling

    LazyHStack arranges items horizontally and works well with horizontal ScrollView.
  4. Final Answer:

    Use ScrollView with LazyHStack and load images lazily inside ForEach -> Option A
  5. Quick Check:

    LazyHStack + ScrollView for large horizontal lists = C [OK]
Hint: Use LazyHStack inside ScrollView for large horizontal lists [OK]
Common Mistakes:
  • Using HStack loads all views immediately
  • Confusing vertical and horizontal stacks
  • Using List when horizontal scrolling is needed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard