Skip to content

Instantly share code, notes, and snippets.

@jeksys
Forked from VAnsimov/HostingView Example.swift
Created July 8, 2021 05:25
Show Gist options
  • Save jeksys/b8bee5e94c937edf3990cc69ed051a16 to your computer and use it in GitHub Desktop.
Save jeksys/b8bee5e94c937edf3990cc69ed051a16 to your computer and use it in GitHub Desktop.
SwiftUI View to UIView
import UIKit
import SwiftUI
// SwiftUI
struct SomeView: View, HostingViewInitialization {
var body: some View {
Text("Hello World!")
}
}
// UIKit
class RootViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// SwiftUI View -> UIView
let uiView = HostingView<SomeView>()
}
}
import UIKit
import SwiftUI
protocol HostingViewInitialization {
init()
}
class HostingView<T: View & HostingViewInitialization>: UIView {
private(set) var hostingController: UIHostingController<T>!
var rootView: T {
get { hostingController.rootView }
set { hostingController.rootView = newValue }
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
}
// MARK: - Private
private extension HostingView {
func setup() {
backgroundColor = .clear
hostingController = UIHostingController(rootView: T.init())
hostingController.view.backgroundColor = backgroundColor
hostingController.view.frame = self.bounds
hostingController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(hostingController.view)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment