Skip to content

Instantly share code, notes, and snippets.

@igmyung
Created May 3, 2023 11:41
Show Gist options
  • Save igmyung/854a717f24c791e96540587db49bd1a6 to your computer and use it in GitHub Desktop.
Save igmyung/854a717f24c791e96540587db49bd1a6 to your computer and use it in GitHub Desktop.
SwiftUI UIViewRepresentable nested view example
import SwiftUI
struct ContentView: View {
@State private var toggle = false
var body: some View {
CustomParentView {
Button {
toggle.toggle()
} label: {
Text(toggle.description)
}
}
}
}
struct CustomParentView<Content: View>: UIViewRepresentable {
let content: Content
@inlinable init(@ViewBuilder content: () -> Content) {
self.content = content()
}
func makeUIView(context: Context) -> UIView {
let view = UIView()
let hostingController = context.coordinator.hostingController
hostingController.view.frame = view.bounds
hostingController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(hostingController.view)
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
context.coordinator.hostingController.rootView = self.content
}
class Coordinator: NSObject {
var hostingController: UIHostingController<Content>
init(hostingController: UIHostingController<Content>) {
self.hostingController = hostingController
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(hostingController: UIHostingController(rootView: content))
}
}
@malhal
Copy link

malhal commented May 24, 2025

This is missing the representable's sizeOf func and hostingController.sizeOptions. Both essential for when the nested SwiftUI View changes its size.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment