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
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)
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { SafeAreaDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
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
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)
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { SafeAreaInsetDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
In the example above, the .safeAreaInset(edge: .bottom) modifier is used to insert UI at the bottom edge of the screen.