I'm using something similar to this 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))
}
}
The only different thing is I'm using UIScrollView
.
When I have a @State width
and call .frame(width)
on the content, the content would stay with initial width even when width is changed.
I tried:
hostingController.sizingOptions = .intrinsicContentSize
This time the size would change to correct size if I pinch zoom the content, but the initial size that trigger updateUIView
would be .zero
. This prevents me to center the content.
Is there a way to dynamically set size and get correct rendering just like any child view of a normal SwiftUI view?