Created
May 3, 2023 11:41
-
-
Save igmyung/854a717f24c791e96540587db49bd1a6 to your computer and use it in GitHub Desktop.
SwiftUI UIViewRepresentable nested view example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Hello @igmyung, did you find a solution for that?