Skip to content

Instantly share code, notes, and snippets.

@nathanborror
Last active January 3, 2023 22:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanborror/c9b92591be70639ab82f757686af0266 to your computer and use it in GitHub Desktop.
Save nathanborror/c9b92591be70639ab82f757686af0266 to your computer and use it in GitHub Desktop.
Custom UIKit view with child SwiftUI views
import UIKit
import SwiftUI
import PlaygroundSupport
// CustomParentView is a custom UIKit view. Its Coordinator can be used
// to manage delegates if needed (e.g. UIContextMenuInteractionDelegate).
struct CustomParentView<Content: View>: UIViewRepresentable {
let content: UIView
@inlinable init(@ViewBuilder content: () -> Content) {
self.content = UIHostingController(rootView: content()).view
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> UIView {
let view = UIView()
view.backgroundColor = .lightGray
content.frame = view.bounds
content.autoresizingMask = [.flexibleWidth, .flexibleHeight]
content.backgroundColor = .clear // unfortunate
view.addSubview(content)
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
// nothing to update
}
class Coordinator: NSObject {
var view: CustomParentView
init(_ view: CustomParentView) {
self.view = view
}
}
}
// ContentView is an example of how to use our CustomParentView
// with child SwiftUI views.
struct ContentView: View {
var body: some View {
CustomParentView {
Text("Test")
.foregroundColor(.white)
}
}
}
let viewController = UIHostingController(rootView: ContentView())
PlaygroundPage.current.liveView = viewController
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment