Last active
August 26, 2021 06:35
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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