From 7e8eaca72eae910d6d3b6272c263c6c3a10b755c Mon Sep 17 00:00:00 2001 From: Hiroshi Kimura Date: Tue, 16 May 2023 13:14:22 +0900 Subject: [PATCH] Add SwiftUIHostingViewController (#5) --- .../SwiftUIHostingViewController.swift | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Sources/SwiftUIHosting/SwiftUIHostingViewController.swift diff --git a/Sources/SwiftUIHosting/SwiftUIHostingViewController.swift b/Sources/SwiftUIHosting/SwiftUIHostingViewController.swift new file mode 100644 index 0000000..8c2e2ac --- /dev/null +++ b/Sources/SwiftUIHosting/SwiftUIHostingViewController.swift @@ -0,0 +1,40 @@ +import SwiftUI + +open class SwiftUIHostingViewController: UIViewController { + + public let configuration: SwiftUIHostingView.Configuration + private let content: (UIViewController) -> AnyView + + public init( + configuration: SwiftUIHostingView.Configuration = .init(), + content: @escaping (Self) -> Content + ) { + self.configuration = configuration + self.content = { AnyView(content(unsafeDowncast($0, to: Self.self))) } + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + open override func viewDidLoad() { + + let _content = content(self) + + let contentView = SwiftUIHostingView(configuration: configuration) { _content } + + view.addSubview(contentView) + contentView.translatesAutoresizingMaskIntoConstraints = false + + NSLayoutConstraint.activate([ + contentView.topAnchor.constraint(equalTo: view.topAnchor), + contentView.rightAnchor.constraint(equalTo: view.rightAnchor), + contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + contentView.leftAnchor.constraint(equalTo: view.leftAnchor), + ]) + + } + +}