Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ryanashcraft/5bccd5f0b21da958d24323cdcb560b9b to your computer and use it in GitHub Desktop.
Save ryanashcraft/5bccd5f0b21da958d24323cdcb560b9b to your computer and use it in GitHub Desktop.
iOS 17-compatible SwiftUI implementation of cellLayoutMarginsFollowReadableWidth
import SwiftUI
@available(watchOS 10.0, *)
@available(iOS 17.0, *)
private struct ContentMarginsFollowReadableWidthModifier: ViewModifier {
static let readableWidth: Double = 672
static let minInsetLength: Double = 16
@ViewBuilder
func body(content: Content) -> some View {
GeometryReader { geometry in
let insetLength = max(Self.minInsetLength, (geometry.size.width - Self.readableWidth) / 2)
content
.contentMargins(.horizontal, insetLength, for: .scrollContent)
}
}
}
public extension View {
@ViewBuilder
func contentMarginsFollowReadableWidth() -> some View {
if #available(iOS 17.0, watchOS 10.0, *) {
self.modifier(ContentMarginsFollowReadableWidthModifier())
} else {
self
}
}
}
@ryanashcraft
Copy link
Author

Example usage:

List {
    Text("Hello, World!")
}
    .contentMarginsFollowReadableWidth()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment