A bottom action button looks correct in every screenshot in the design review. Then someone rotates the phone, drags the iPad window to a third of the screen, or presents the same view in a sheet, and the button sits too high, too low, or half under the home indicator.

When I open the code, I usually find the same assumption written in different ways: a constant named bottomSafeArea = 34, a lookup keyed on device model, or a value read from the key window at launch and stored. Each one says "the app knows the device, so it knows the insets."

It does not. A safe area describes the unobstructed region of one particular view, in its current position in the hierarchy, right now. The same view controller has different insets full screen, in a sheet, inside a split view column, and in a resized window, on the same device, within the same minute.

Decide what each layer is protecting

A reading screen has at least three layout requirements, and they do not call for the same inset:

  1. The background should run edge to edge, behind the status bar and the home indicator.
  2. The text should stay clear of obstructions and keep a comfortable line length.
  3. The primary action should remain reachable and never be covered.

Before adding padding, I name what it is for. In practice five different things end up in a constant called bottomPadding:

  • a system obstruction (home indicator, sensor housing, window controls);
  • a bar the app itself owns;
  • visual spacing from the design;
  • the keyboard;
  • a readable-width margin.

Each has a different owner and changes at a different time. Merge them into one number and the first design change makes it impossible to tell which part to adjust.

UIKit: constrain to the guide, never to a number

In UIKit the relationship is expressed with layout guides, so it stays correct when the geometry changes:

SwiftGitHub
import UIKit

@MainActor
final class ReadingViewController: UIViewController {
    private let actionButton = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground

        actionButton.setTitle("Continue reading", for: .normal)
        actionButton.titleLabel?.adjustsFontForContentSizeCategory = true
        actionButton.titleLabel?.numberOfLines = 0
        actionButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(actionButton)

        let safeArea = view.safeAreaLayoutGuide
        let aboveKeyboard = actionButton.bottomAnchor.constraint(
            lessThanOrEqualTo: view.keyboardLayoutGuide.topAnchor,
            constant: -12
        )
        let restingPosition = actionButton.bottomAnchor.constraint(
            equalTo: safeArea.bottomAnchor,
            constant: -12
        )
        restingPosition.priority = .defaultHigh

        NSLayoutConstraint.activate([
            actionButton.leadingAnchor.constraint(
                equalTo: safeArea.leadingAnchor, constant: 20
            ),
            actionButton.trailingAnchor.constraint(
                equalTo: safeArea.trailingAnchor, constant: -20
            ),
            actionButton.heightAnchor.constraint(
                greaterThanOrEqualToConstant: 44
            ),
            aboveKeyboard,
            restingPosition
        ])
    }
}

The 20 and 12 are design spacing, measured from the safe area. They are added to the system's inset and never stand in for it.

The two bottom constraints separate two concerns. The button rests 12 points above the safe area at high priority, and is required to stay above the keyboard. With no keyboard on screen, the top of keyboardLayoutGuide rests on the bottom of the safe area, so both constraints agree. When the keyboard appears, the required constraint takes over and the system animates the change with the keyboard. There is no notification observer and no arithmetic converting a keyboard frame between coordinate spaces, which is where most hand-written keyboard handling goes wrong.

The label allows multiple lines and the height is a minimum. "Continue reading" is short in English; its German or Finnish translation at the largest accessibility text size is not.

Sometimes you do need the numbers, for custom drawing or a manually laid out layer. Then read them where UIKit tells you they changed:

SwiftGitHub
final class WaveformViewController: UIViewController {
    private let waveformLayer = CALayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.layer.addSublayer(waveformLayer)
    }

    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        view.setNeedsLayout()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        waveformLayer.frame = view.bounds.inset(by: view.safeAreaInsets)
    }
}

safeAreaInsets is zero in viewDidLoad, because the view is not in a window yet. Code that reads it there and caches the result is the origin of many "works on second launch" reports.

Leading is a reading direction; left is a side of the glass

leading and trailing follow the layout direction: in Arabic or Hebrew, leading is on the right. left and right are physical. Both are correct, for different things.

A row with a title and a disclosure chevron should mirror, so it uses leading and trailing. A waveform's time axis, a media scrubber, a map, or a control positioned next to a physical button should not mirror. Replacing every left with leading across a project is a mechanical change that breaks the second group.

The safe area itself is physical. UIEdgeInsets has left and right because an obstruction sits on a side of the hardware regardless of the language. When a layout model of your own needs directional values, convert with the layout direction in hand:

SwiftGitHub
extension NSDirectionalEdgeInsets {
    init(_ insets: UIEdgeInsets, layoutDirection: UITraitEnvironmentLayoutDirection) {
        let isRightToLeft = layoutDirection == .rightToLeft
        self.init(
            top: insets.top,
            leading: isRightToLeft ? insets.right : insets.left,
            bottom: insets.bottom,
            trailing: isRightToLeft ? insets.left : insets.right
        )
    }
}

Use the view's effectiveUserInterfaceLayoutDirection or its trait collection as the source. The device language is the wrong input: a view can force a direction through semanticContentAttribute, and a left-to-right app can embed right-to-left content.

This is the literal case in the title. Any container can make the two sides differ: a parent that sets asymmetric additionalSafeAreaInsets for a floating panel on one edge, for example, gives its children a left inset that is not the right inset. Code that reads one of them and applies it to both sides is wrong in exactly those configurations and looks right everywhere else.

To test, run with the right-to-left pseudolanguage from the scheme's options. Changing only the text language in a preview leaves most direction bugs hidden.

SwiftUI: each layer states its own policy

SwiftUI respects the safe area by default, and the modifiers let each layer opt in or out separately:

SwiftGitHub
import SwiftUI

struct Paragraph: Identifiable {
    let id: UUID
    let text: String
}

struct ReadingScreen: View {
    let paragraphs: [Paragraph]
    let continueReading: () -> Void

    var body: some View {
        ScrollView {
            LazyVStack(alignment: .leading, spacing: 18) {
                ForEach(paragraphs) { paragraph in
                    Text(paragraph.text)
                        .frame(maxWidth: .infinity, alignment: .leading)
                }
            }
            .frame(maxWidth: 680)
            .padding(.horizontal, 20)
            .padding(.vertical, 24)
            .frame(maxWidth: .infinity)
        }
        .background {
            Color(uiColor: .systemBackground)
                .ignoresSafeArea()
        }
        .safeAreaInset(edge: .bottom, spacing: 0) {
            Button("Continue reading", action: continueReading)
                .frame(maxWidth: .infinity)
                .padding()
                .background(.bar)
        }
    }
}

Three policies are visible, one per requirement from the list at the top.

The background ignores the safe area, and only the background does. ignoresSafeArea() is applied to the Color inside .background, so the scroll view and its content keep respecting it.

The text is limited to 680 points for line length and then centered in whatever width is available. That limit is a readability decision and has nothing to do with obstructions.

The button is placed with safeAreaInset(edge: .bottom). This does two things at once: it positions the bar above the home indicator, and it shrinks the safe area that the scroll view sees by the bar's height. The last paragraph can therefore scroll fully above the bar, and content still appears behind the bar's material while scrolling. An overlay or a ZStack would draw the bar in the same place and leave the last lines of the article permanently underneath it.

Modifier order is the usual source of surprises. ignoresSafeArea() on the ScrollView itself, or on a container above it, changes the layout of everything inside, including controls that then slide under the status bar. Apply it to the smallest view that should extend.

Paragraphs have stable identifiers here. ForEach(paragraphs.indices, id: \.self) compiles and works until the array is edited, at which point SwiftUI associates state and animations with positions instead of paragraphs.

Double compensation

A very common inset bug is correct code applied twice.

A UIScrollView already adjusts for the safe area: contentInsetAdjustmentBehavior defaults to .automatic, and the result is visible in adjustedContentInset, which is contentInset plus what the system added. A developer sees content under the home indicator in some intermediate state, sets contentInset.bottom = view.safeAreaInsets.bottom, and the same obstruction is now compensated twice: on a phone with a 34-point bottom inset, 68 points of space where 34 were needed. In portrait the gap reads as generous padding. In landscape or in a sheet it is obviously wrong, and someone "fixes" it with a device check.

The SwiftUI version is .padding(.bottom, proxy.safeAreaInsets.bottom) on content that already respects the safe area, or a bar placed with safeAreaInset plus manual padding of the bar's height on the scroll content.

When a layout has too much or too little space, I list each contribution by the five names from earlier and ask which component applies it. If two of them describe the same obstruction, that is the bug. A debug overlay makes the system's share visible while you check:

SwiftGitHub
struct SafeAreaProbe: ViewModifier {
    func body(content: Content) -> some View {
        content.overlay {
            GeometryReader { proxy in
                let insets = proxy.safeAreaInsets
                Text(
                    "top \(Int(insets.top))  bottom \(Int(insets.bottom))\n"
                    + "leading \(Int(insets.leading))  trailing \(Int(insets.trailing))\n"
                    + "size \(Int(proxy.size.width)) × \(Int(proxy.size.height))"
                )
                .font(.caption2.monospaced())
                .padding(6)
                .background(.yellow.opacity(0.85))
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .allowsHitTesting(false)
            }
        }
    }
}

extension View {
    func safeAreaProbe() -> some View { modifier(SafeAreaProbe()) }
}

Attach it to the view you are debugging, in debug builds, and rotate. Watching the numbers change per container is the quickest way I know to stop thinking of insets as a property of the device.

The window is the unit of layout

UIScreen.main.bounds and "the first window of the first scene" describe the display or some window, and they have been the wrong inputs since iPad multitasking arrived. An app can have several scenes of different sizes on screen at once, on an external display, or in a resizable window. A view in a sheet or a popover has less room than the window that presents it.

Lay out from what the view actually receives: its bounds, its trait collection, its safe area, and in SwiftUI the size proposed to it. Keep idiom checks for real capability differences, such as whether a pointer or a camera is available.

Size classes need the same caution. A regular horizontal size class tells you the window is not compact. It does not tell you a detail column inside that window is wide enough for two columns of cards. Decide from the measured width of the container, with ViewThatFits, a custom Layout, or a geometry reading, and the view keeps working when it is reused somewhere narrower.

The keyboard needs a policy of its own

The keyboard covers content, changes height with the input type and the suggestion bar, and can be undocked or floating on iPad, in which case there is no bottom strip to avoid at all. A stored "keyboard height" is wrong in each of those cases.

In UIKit, keyboardLayoutGuide tracks the docked keyboard as shown above; set followsUndockedKeyboard when the layout should follow a floating one too. In SwiftUI, the keyboard is part of the safe area by default, so content moves automatically; ignoresSafeArea(.keyboard) opts a specific view out, for example a background image that should not jump.

Before choosing the mechanism, decide the behavior. An editor wants the insertion point visible and can let decoration disappear behind the keyboard. A login form wants the submit button visible with the field. A chat wants the input bar attached to the keyboard and the message list to shrink. These are three different layouts, and "move everything up by the keyboard height" serves none of them well.

Test the transitions

A layout can be correct in portrait and in landscape and still pass through a wrong state between them. Still screenshots of endpoints miss that. My manual pass for a screen like this:

  • rotate with the keyboard visible;
  • drag the iPad window edge slowly from full width to the minimum;
  • present the screen in a sheet, then change the sheet's detent;
  • set the largest accessibility text size, then the right-to-left pseudolanguage;
  • connect a hardware keyboard, so the software keyboard collapses to its toolbar;
  • use the longest localized title for the action;
  • with VoiceOver on, confirm the action is reachable and in a sensible order.

Watch the button through each transition, not only before and after. A control that spends 300 milliseconds under the home indicator during rotation is a bug that users find by tapping at the wrong moment.

What to ask of your own layouts

  • Is there any stored or hard-coded inset, or a lookup by device model?
  • For each padding value, which of the five purposes does it serve?
  • Is any obstruction compensated for by both the system and your code?
  • Does anything read screen bounds or the key window to make a layout decision?
  • Should each left/right in the code mirror in a right-to-left interface?

"How big is the safe area on this device?" has no stable answer. Ask which view owns the geometry and what should happen when it changes.

References

If this edition sharpened your next review, you can buy me a coffee.