SwiftUI Layout Spacers & Alignment

SwiftUI Layout: Spacers & Alignment

Use Spacer() to distribute content and alignment parameters to control placement.


Spacers

Use Spacer() to distribute content and alignment parameters to control placement.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct SpacersAlignmentDemo: View {
  var body: some View {
HStack {
  Text("Left"); Spacer(); Text("Right")
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
} }


Vertical Alignment and Guides

Align text baselines and customize positioning with alignment and alignmentGuide.

Syntax:

  • HStack(alignment: .firstTextBaseline) { ... }
  • .alignmentGuide(.firstTextBaseline) { d in d[.bottom] }
  • VStack(alignment: .leading) { Spacer() }

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct AlignmentGuideDemo: View {
  var body: some View {
VStack(alignment: .leading, spacing: 16) {
  HStack(alignment: .firstTextBaseline, spacing: 8) {
    Text("Title").font(.title)
    Text("Aligned").alignmentGuide(.firstTextBaseline) { d in d[.bottom] }
  }
  HStack {
    Text("Left"); Spacer(); Text("Right")
  }
}
.padding()
} }

Comments

Leave a Reply

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