Skip to main content

How to add extra padding to the safe area

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to add extra padding to the safe area 관련

SwiftUI by Example

Back to Home

How to add extra padding to the safe area | SwiftUI by Example

How to add extra padding to the safe area

Updated for Xcode 15

New in iOS 17

SwiftUI's safeAreaPadding() modifier insets the safe area by some amount of your choosing, either on all edges or on a subset. When dealing with scrolling content this behaves differently from using the plain padding() modifier, because it will inset the contents of the scroll view rather than the scroll view itself.

First, here'a simple example that draws a red circle to fill all the safe area, minus 50 points on each side:

Circle()
    .fill(.red)
    .safeAreaPadding(50)

Download this as an Xcode projectopen in new window

You can request only some edges by adding a second parameter, like this:

Circle()
    .fill(.red)
    .safeAreaPadding(.horizontal, 50)

Download this as an Xcode projectopen in new window

And for complete control, you can pass in an EdgeInsets object to get exact insets on all four edges:

Circle()
    .fill(.red)
    .safeAreaPadding(.init(top: 20, leading: 50, bottom: 20, trailing: 50))

Download this as an Xcode projectopen in new window

Things get more interesting when we apply safeAreaPadding() to a ScrollView, because it ensures our content starts away from the screen edge but still scrolls next to it:

ScrollView(.horizontal) {
    HStack {
        ForEach(0..<10) { i in
            Circle()
                .frame(width: 50, height: 50)
        }
    }
}
.safeAreaPadding(50)

Download this as an Xcode projectopen in new window

Similar solutions…
How to place content outside the safe area | SwiftUI by Example

How to place content outside the safe area
How to inset the safe area with custom content | SwiftUI by Example

How to inset the safe area with custom content
How to control spacing around individual views using padding | SwiftUI by Example

How to control spacing around individual views using padding
How to color the padding around a view | SwiftUI by Example

How to color the padding around a view

이찬희 (MarkiiimarK)
Never Stop Learning.