Skip to content

Instantly share code, notes, and snippets.

@JosephDuffy
Created August 27, 2021 18:07
Show Gist options
  • Select an option

  • Save JosephDuffy/097ecb8f48d30c57f18f2e5730c66d2b to your computer and use it in GitHub Desktop.

Select an option

Save JosephDuffy/097ecb8f48d30c57f18f2e5730c66d2b to your computer and use it in GitHub Desktop.

Revisions

  1. JosephDuffy created this gist Aug 27, 2021.
    33 changes: 33 additions & 0 deletions ReadableWidthView.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    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
    }
    }