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)")…