SwiftUI Layout Safe Area

SwiftUI Layout: Safe Area

Control content under system bars with .ignoresSafeArea() and .safeAreaInset().


Safe Area

Use .ignoresSafeArea() to control content under system bars.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct SafeAreaDemo: View {
  var body: some View {
ZStack {
  LinearGradient(colors: [.blue, .purple], startPoint: .top, endPoint: .bottom)
    .ignoresSafeArea()
  Text("Hello safe area")
    .padding()
    .background(.ultraThinMaterial)
    .cornerRadius(8)
}
} }

In the example above, the .ignoresSafeArea() modifier is used to control content under system bars.



Safe Area Insets

Insert UI at the edges (like a toolbar) using .safeAreaInset.

Syntax:

  • .safeAreaInset(edge: .bottom) { content }

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct SafeAreaInsetDemo: View {
  var body: some View {
ZStack {
  LinearGradient(colors: [.purple, .pink], startPoint: .top, endPoint: .bottom)
    .ignoresSafeArea()
  Text("Content").padding().background(.ultraThinMaterial, in: Capsule())
}
.safeAreaInset(edge: .bottom) {
  HStack {
    Image(systemName: "house.fill"); Spacer(); Image(systemName: "gear")
  }
  .padding()
  .background(.regularMaterial)
}
} }

Comments

Leave a Reply

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