Skip to content

Instantly share code, notes, and snippets.

@JosephDuffy
Created August 27, 2021 18:07
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 JosephDuffy/097ecb8f48d30c57f18f2e5730c66d2b to your computer and use it in GitHub Desktop.
Save JosephDuffy/097ecb8f48d30c57f18f2e5730c66d2b to your computer and use it in GitHub Desktop.
public struct ReadableWidthView<Content: View>: UIViewControllerRepresentable {
public typealias UIViewControllerType = UIViewController
private let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
public func makeUIViewController(context: Context) -> UIViewController {
let viewController = UIViewController()
let view = viewController.view!
let hostingController = UIHostingController(rootView: content)
viewController.addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.view?.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
hostingController.view.topAnchor.constraint(equalTo: view.readableContentGuide.topAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor),
hostingController.view.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.readableContentGuide.bottomAnchor),
])
hostingController.didMove(toParent: viewController)
return viewController
}
public func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
guard let hostingController = uiViewController.children.lazy.compactMap({ $0 as? UIHostingController<Content> }).first else { return }
hostingController.rootView = content
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment