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

Demo.swift

ContentView.swift

App.swift

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()
}
} }

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

Demo.swift

ContentView.swift

App.swift

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()
}
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *