SwiftUI의 뷰 계층에서 UIKit을 사용하기 위한 방법으로 UIViewRepresentable, UIViewControllerRepresentable 을 제공.
(https://swifty-cody.tistory.com/44)
반대로 UIKit 뷰 계층에서 SwiftUI를 사용하기 위한 방법으로 UIHostingViewController를 제공함.
https://developer.apple.com/documentation/swiftui/uihostingcontroller
UIHostingController | Apple Developer Documentation
A UIKit view controller that manages a SwiftUI view hierarchy.
developer.apple.com
UIHostingViewController는 SwiftUI의 View를 rootView로 주입받아서
UIViewController의 view처럼 호스팅해줌.
UIHostingViewController의 예시.
import UIKit
import SwiftUI
// SomeSwiftUIView를 호스팅해주는 UIHostingController
class SomeHostingViewController: UIHostingController<SomeSwiftUIView> {
override func viewDidLoad() {
super.viewDidLoad()
}
}
struct SomeSwiftUIView: View {
var body: some View {
VStack(alignment: .leading) {
Text("Some SwiftUI View")
}
}
}
#Preview {
SomeSwiftUIView()
}

이 UIHostingController는 UIKit 뷰 계층에서 UIViewController처럼 사용할 수 있음.
예시.
class ViewController: UIViewController {
private let button: UIButton = {
let button = UIButton()
button.setTitle("SwiftUI View 띄우기", for: .normal)
button.setTitleColor(.systemBlue, for: .normal)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupView()
}
func setupView() {
view.addSubview(button)
button.addTarget(self, action: #selector(tapButton), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
@objc private func tapButton() {
// SomeHostingViewController를 present
present(SomeHostingViewController(rootView: SomeSwiftUIView()), animated: true)
}
}
