我找到的解决方案是将我的SwiftUI视图传递给重叠的
UIViewControllerRepresentable
。使这一切成为可能的方法是使涉及的所有实体都通用,并在您的可表示中使用
@ViewBuilder
。
通过使用视图修饰符而不是在可表示中包装内容,可以使此过程更加简洁。
ContentView
struct ContentView: View {
var body: some View {
ViewControllerRepresentable {
Text("SwiftUI Content")
}
}
}
UIViewControllerRepresentable
struct ViewControllerRepresentable<Content: View>: UIViewControllerRepresentable {
@ViewBuilder let content: Content
typealias UIViewControllerType = ViewController<Content>
func makeUIViewController(context: Context) -> BottomSheetViewController<Content> {
ViewController<Content>(content: UIHostingController(rootView: content))
}
func updateUIViewController(_ uiViewController: ViewController<Content>, context: Context) {
}
}
UIViewController
import SwiftUI
import UIKit
final class ViewController<Content: View>: UIViewController {
private let content: UIHostingController<Content>
init(content: UIHostingController<Content>) {
self.content = content
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
return nil
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
setupLayout()
}
private func setupLayout() {
addChild(content)
view.addSubview(content.view)
content.didMove(toParent: self)
NSLayoutConstraint.activate([
content.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
content.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
content.view.topAnchor.constraint(equalTo: view.topAnchor),
content.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}