Mastering Swift and SwiftUI

Insights, Tips, and Tutorials for iOS Developers

SwiftUI Modifiers Deep Dive: safeAreaPadding

Published on Feb 5, 2025

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 17.0+

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

Apple's Documentation

Use this modifier when you would like to add a fixed amount of space to the safe area a view sees.

Example:

ScrollView(.horizontal) {
    HStack(spacing: 10.0) {
        ForEach(items) { item in
            ItemView(item)
        }
    }
}
.safeAreaPadding(.horizontal, 20.0)

Usage

The safeAreaPadding modifier is useful when you want to add spacing around views while respecting the safe area. The easiest and most useful example to demonstrate it would be when using ScrollViews.

For example, let's say we have a horizontal ScrollView, that has an array of colored squares. If we wanted to add padding to the edges of the ScrollView, we might do something like this:

struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal) {
            HStack(spacing: 10.0) {
                ForEach(0..<100) { index in
                    Color(
                        hue: Double(index) / 100,
                        saturation: 1,
                        brightness: 1
                    )
                    .aspectRatio(1.0, contentMode: .fit)
                    .frame(width: 100)
                }
            }
        }
        .scrollIndicators(.hidden)
        .padding(.horizontal, 20.0)
    }
}

But the issue with the above, is that the padding will pad the ScrollView itself, leading to clipping the edges of the ScrollView when scrolling. If we switch the padding modifier to use safeAreaPadding instead, we get a slightly different experience:

struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal) {
            HStack(spacing: 10.0) {
                ForEach(0..<100) { index in
                    Color(
                        hue: Double(index) / 100,
                        saturation: 1,
                        brightness: 1
                    )
                    .aspectRatio(1.0, contentMode: .fit)
                    .frame(width: 100)
                }
            }
        }
        .scrollIndicators(.hidden)
        .safeAreaPadding(.horizontal, 20.0) // Change this to safeAreaPadding instead
    }
}

Here's a demo of the two modifiers side by side:

Regular Padding Demo FullSafe Area Padding Demo Full

And that's how you can use safeAreaPadding to improve layout consistency!