Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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