SwiftUI Layout GeometryReader

SwiftUI Layout: GeometryReader

Read parent size and position to build responsive layouts with GeometryReader.


GeometryReader

Use GeometryReader to read parent size and position to build responsive layouts.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct GeometryDemo: View {
  var body: some View {
GeometryReader { geo in
  VStack(spacing: 12) {
    Text("Width: \(Int(geo.size.width))")
    Text("Height: \(Int(geo.size.height))")
  }
  .frame(maxWidth: .infinity, maxHeight: .infinity)
}
.background(.orange.opacity(0.1))
} }


Responsive Positioning

Position elements based on container size using GeometryReaderalignment, and offset.

Syntax:

  • GeometryReader { geo in ... }
  • .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
  • .offset(x: 0, y: -12)

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct GeometryPositionDemo: View {
  var body: some View {
GeometryReader { geo in
  ZStack {
    Color.orange.opacity(0.1)
    Text("Bottom Right")
      .padding(8)
      .background(.thinMaterial, in: Capsule())
      .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
      .offset(x: 0, y: -12)
  }
}
} }

Comments

Leave a Reply

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