Mastering Swift and SwiftUI

Insights, Tips, and Tutorials for iOS Developers

SwiftUI Modifiers Deep Dive: safeAreaInset

Published on Oct 2, 2024

Get a quick glimpse of how Tiny Currency simplifies currency conversion with up to date rates, multi-currency support, and easy-to-use widgets. Perfect for on-the-go use, our app ensures you're always prepared, no matter where your travels take you.

📱 iOS 15.0+

On this deep dive, we are exploring the safeAreaInset SwiftUI modifier, which was added in iOS 15.0.

Apple's Documentation

The content view is anchored to the specified vertical edge in the parent view, aligning its horizontal axis to the specified alignment guide. The modified view is inset by the height of content, from edge, with its safe area increased by the same amount.

Note that there is also an alternate function for Horizontal alignment

Example:

struct ScrollableViewWithBottomBar: View {
    var body: some View {
        ScrollView {
            ScrolledContent()
        }
        .safeAreaInset(edge: .bottom, spacing: 0) {
            BottomBarContent()
        }
    }
}

Usage

So what would be a simple use case for this modifier?

Well many apps these days showcase large style buttons at the bottom of the screen for continuing to the next screen.

Using the example shown by Apple's documentation, we can build something like this:

struct ContentView: View {
    var body: some View {
        ScrollView {
            VStack(spacing: 0) {
                ForEach(0..<300) { index in
                    Color(hue: CGFloat(index) / 300.0, saturation: 1, brightness: 1)
                }
            }
        }
        .safeAreaInset(edge: .bottom) {
            Button("Continue") {
                
            }
            .buttonStyle(.borderedFullWidth)
            .background(.regularMaterial)
        }
    }
}

The above use case is a really simple one. We have a scrolling list of colors, and I want to add a button to the bottom, but I want it to respect the safe area.

Well, I can add a button using the safeAreaInset modifier, specify that it's for the bottom edge, and give it a material background so it can go on top of my scrolling content.

Let's see what it looks like:

Light Demo FullDark Demo Full

And there you have it! A really simple use case for using safeAreaInset.