Skip to content

Instantly share code, notes, and snippets.

@bwhiteley
Last active June 16, 2023 04:47
Show Gist options
  • Save bwhiteley/33aba241ff9986c1eb7bc055a9ab9e33 to your computer and use it in GitHub Desktop.
Save bwhiteley/33aba241ff9986c1eb7bc055a9ab9e33 to your computer and use it in GitHub Desktop.
Host SwiftUI in a UIView
import Foundation
import SwiftUI
#if os(macOS)
public typealias PlatformViewType = NSView
#elseif !os(watchOS)
import UIKit
public typealias PlatformViewType = UIView
#endif
#if !os(watchOS)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
open class HostingView<Content> : PlatformViewType where Content : View {
#if os(macOS)
typealias HostingController = NSHostingController
#else
typealias HostingController = UIHostingController
#endif
private let hostingVC: HostingController<Content>
public var rootView: Content {
get { return hostingVC.rootView }
set { hostingVC.rootView = newValue }
}
public init(rootView: Content) {
self.hostingVC = HostingController(rootView: rootView)
super.init(frame: .zero)
addSubview(hostingVC.view)
hostingVC.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
hostingVC.view.topAnchor.constraint(equalTo: self.topAnchor),
hostingVC.view.bottomAnchor.constraint(equalTo: self.bottomAnchor),
hostingVC.view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
hostingVC.view.trailingAnchor.constraint(equalTo: self.trailingAnchor)
])
}
@available(*, unavailable)
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment