The contentMargins view modifier insets a view's scrollable content without moving its
scrollbar or toolbars. It is the SwiftUI answer to UIKit's readableContentGuide: a full-width
list on iPad reads badly, and this narrows the content only.
Why safeAreaPadding Is Not Enough
Padding the safe area does center the content, but the scroll indicator moves with it, landing in the middle of the screen.
@Environment(\.horizontalSizeClass) private var sizeClass
List {
ForEach(1..<100) { index in
Text("Item \(index)")
}
}
.safeAreaPadding(.horizontal, sizeClass == .regular ? 200 : 0)
Shifting Only the Content
contentMargins takes the edges, the amount, and a ContentMarginPlacement. With
.scrollContent, the rows shift and the scrollbar stays on the trailing edge.
List {
ForEach(1..<100) { index in
Text("Item \(index)")
}
}
.contentMargins(
.horizontal,
sizeClass == .regular ? 200 : 0,
for: .scrollContent
)
The Parameters
- Edges:
leading,trailing,top,horizontal,vertical, orall. - Amount: points to inset by; gate it on
horizontalSizeClassso iPhone keeps full width. - Placement:
.scrollContentmoves the content only;.scrollIndicatorsmoves only the indicator.