Skip to content

Commit

Permalink
Add SwiftUIHostingViewController (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
muukii authored May 16, 2023
1 parent 064204f commit 7e8eaca
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Sources/SwiftUIHosting/SwiftUIHostingViewController.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import SwiftUI

open class SwiftUIHostingViewController: UIViewController {

public let configuration: SwiftUIHostingView.Configuration
private let content: (UIViewController) -> AnyView

public init<Content: View>(
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),
])

}

}

0 comments on commit 7e8eaca

Please sign in to comment.