Member-only story
SwiftUI’s LazyVStack vs. VStack
There’s an Iterator…and…
Difficulty: Beginner | Easy | Normal | Challenging
Terminology:
VStack
: A staple SwiftUI container view that arranges its child views in a vertical stack. VStack
is eager in its rendering approach, meaning it creates all of its child views as soon as the VStack
is rendered. This can make for simpler code and more predictable layouts, but can lead to performance issues with large numbers of child views.
LazyVStack
: A container view that arranges its child views in a vertical line. Unlike VStack
, LazyVStack
does not create its views all at once. Instead, it creates them lazily, only as they are needed for display. This can lead to performance improvements, especially with large numbers of views.
The Basic Syntax
I’ve whacked both a VStack
and a LazyVStack
into some simple project code.
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
VStack(alignment: .center, spacing: 10) {
Text("Top View")
Divider()
Text("Bottom View")
}
LazyVStack(alignment: .center, spacing: 20) {
ForEach(0..<10) { index in
Text("Row \(index)")
}
}
}
.padding()
}
}
#Preview {
ContentView()
}
As you can see the top example is using a VStack
to layout two views vertically
VStack(alignment: .center, spacing: 10) {
Text("Top View")
Divider()
Text("Bottom View")
}
The lazy version shows that LazyVStack
has similar syntax but we need to remember that this has lazy rendering behavior. Although not shown here, a LazyVStack
is typically used within a ScrollView since its lazy nature becomes advantageous with scrollable content as all of the content is not usually available on the screen.:
LazyVStack(alignment: .center, spacing: 20) {
ForEach(0..<10) { index in
Text("Row \(index)")
}
}
Both VStack
and LazyVStack
provide essential functionality for vertical layouts in SwiftUI applications. The choice between them depends on the specific needs…