Skip to content

Instantly share code, notes, and snippets.

@igmyung
Created May 3, 2023 11:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment