fairly new to SwiftUI, so thank you in advance. Inside the init of the Coordinator we pass the WebView to let the Coordinator know who the parent is, but the WebView being a struct, wouldn't Coordinator be having a new copy of the WebView instead of the original?
If so, why is this approach commonly mentioned? Would it be better to create a new class(ObservableObject) and let WebView create an object of the class and pass the class into the Coordinator?
struct WebView: UIViewRepresentable {
var url: URL
func makeCoordinator() -> WebView.Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> WKWebView {
let view = WKWebView()
view.navigationDelegate = context.coordinator
view.load(URLRequest(url: url))
return view
}
func updateUIView(_ uiView: WKWebView, context: Context) {}
class Coordinator: NSObject, WKNavigationDelegate {
var parent: WebView
init(_ parent: WebView) {
self.parent = parent
}
}
}
Yes,
Coordinatorholds a copy of originalWebView, you understand it right. But its purpose is not what you think.First, you need to understand that
WebViewdoesn't holdWKWebView, its purpose is giving information how to updateWKWebViewto fit your intent, andCoordinatoris helping it by keeping a copy ofWebViewHow is it helping ? Usually to track old version (latest version, or first version) of
WebViewso you can get its infomations if neededHere's another small example you can see on Preview how
UIViewRepresentableworks