Skip to content

Instantly share code, notes, and snippets.

@mbernson
Last active August 26, 2021 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbernson/c448ef1a6d3ca803662f573bab9dd849 to your computer and use it in GitHub Desktop.
Save mbernson/c448ef1a6d3ca803662f573bab9dd849 to your computer and use it in GitHub Desktop.
SwiftUI view modifier that constrains the width of a view to be no bigger than the readable width.
import SwiftUI
/// View modifier that constrains the width of a view to be no bigger than the readable width.
struct ReadableContentWidth: ViewModifier {
private let measureViewController = UIViewController()
@State private var orientation: UIDeviceOrientation = UIDevice.current.orientation
func body(content: Content) -> some View {
content
.frame(maxWidth: readableWidth(for: orientation))
.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
orientation = UIDevice.current.orientation
}
}
private func readableWidth(for orientation: UIDeviceOrientation) -> CGFloat {
measureViewController.view.frame = UIScreen.main.bounds
let readableContentSize = measureViewController.view.readableContentGuide.layoutFrame.size
return readableContentSize.width
}
}
extension View {
func readableContentWidth() -> some View {
modifier(ReadableContentWidth())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment