SwiftUI Layout Lazy Stacks
SwiftUI Layout: Lazy Stacks
Use LazyVStack/LazyHStack to efficiently render large lists of views on demand.
Lazy Stacks
Lazy Stacks are used to efficiently render large lists of views on demand.
Syntax:
LazyVStack { ForEach(...) { ... } }LazyHStack { ForEach(...) { ... } }
Example
import SwiftUI
struct LazyStacksDemo: View {
var body: some View {
ScrollView {
LazyVStack(spacing: 8) {
ForEach(1...100, id: \.self) { i in
Text("Row \(i)").frame(maxWidth: .infinity, alignment: .leading).padding(8)
.background(.gray.opacity(0.1)).cornerRadius(6)
}
}.padding()
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { LazyStacksDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
In the example above, the LazyVStack is used to efficiently render a large list of views on demand.
Horizontal Lazy Stack
Use LazyHStack inside a horizontal ScrollView for efficient carousels.
Syntax:
ScrollView(.horizontal) { LazyHStack { ForEach(...) { ... } } }
Example
import SwiftUI
struct LazyHStackDemo: View {
var body: some View {
ScrollView(.horizontal) {
LazyHStack(spacing: 12) {
ForEach(1...50, id: \.self) { i in
Text("Card \(i)")
.padding(16)
.background(.blue.opacity(0.1))
.cornerRadius(8)
}
}.padding()
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { LazyHStackDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
In the example above, the LazyHStack is used inside a horizontal ScrollView for efficient carousels.