SwiftUI Layout Stacks

SwiftUI Layout: Stacks

Arrange views vertically, horizontally, or in layers using VStackHStack, and ZStack.


Examples

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct StackDemo: View {
  var body: some View {
VStack(spacing: 12) {
  Text("Title").font(.title)
  HStack {
    Text("Left")
    Spacer()
    Text("Right")
  }
  ZStack {
    Color.blue.opacity(0.1)
    Text("Overlay")
  }
}.padding()
} }


Overlays and Alignment

Layer content with ZStack and control placement using alignment and alignmentGuide.

Syntax:

  • ZStack(alignment: .topLeading) { ... }
  • .alignmentGuide(.top) { d in d[.bottom] }

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct OverlayDemo: View {
  var body: some View {
ZStack(alignment: .topLeading) {
  Image(systemName: "rectangle.fill").resizable().foregroundStyle(.blue.opacity(0.15))
  Text("Badge")
    .padding(6)
    .background(.ultraThinMaterial, in: Capsule())
    .alignmentGuide(.top) { d in d[.bottom] } // custom guide
}
.frame(width: 220, height: 120)
.padding()
} }

Comments

Leave a Reply

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