Skip to content
DeveloperMemos

How to Make a VStack Scrollable in SwiftUI

SwiftUI, Scrollable VStack1 min read

If you've been working with SwiftUI, you might have encountered a situation where you needed to display a list of items within a VStack that exceeds the available vertical space on the screen. When this happens, making the VStack scrollable becomes essential. In this tutorial, we'll delve into how to achieve just that in a few simple steps.

Prerequisites

Before we begin, it's assumed that you have a basic understanding of SwiftUI and Xcode. If not, don't worry; I'll walk you through the process step by step.

Creating a Scrollable VStack

To make a VStack scrollable, you need to embed it within a ScrollView. This allows the VStack to be placed within the scrolling container, enabling the user to navigate through its contents when they exceed the visible area.

Here's a simple example of how to create a scrollable VStack:

1import SwiftUI
2
3struct ScrollableVStackExample: View {
4 var body: some View {
5 ScrollView {
6 VStack {
7 ForEach(1..<21) { index in
8 Text("Item \(index)")
9 .padding()
10 }
11 }
12 }
13 }
14}

In this example, the VStack containing 20 text items is embedded within a ScrollView. As a result, if the number of items extends beyond the screen's height, the user can scroll through the content.

Using LazyVStack for Efficiency

When dealing with a large number of items or dynamic data, using a LazyVStack is more efficient as it only creates views for elements that are currently visible on the screen. This can significantly improve the performance of your app, especially when dealing with extensive lists.

Let's take a look at an example using a LazyVStack:

1import SwiftUI
2
3struct LazyVStackExample: View {
4 var body: some View {
5 ScrollView {
6 LazyVStack {
7 ForEach(1..<100) { index in
8 Text("Item \(index)")
9 .padding()
10 }
11 }
12 }
13 }
14}

By simply replacing the VStack with LazyVStack, you can enhance the efficiency of displaying long lists or dynamic content within your app.