I want to show a WKWebView in a SwiftUI view hierarchy, and I want to control the WKWebView using buttons implemented in SwiftUI.
I can do this by creating a SwiftUI
I think the best way is to leverage the power of Combine by creating a PassthroughSubject
on your parent view and then subscribe to events in your child WebView
.
First, create a struct in your UIViewReprsentable
that captures the available events you want to send to your WebView
:
struct WebView: UIViewRepresentable {
enum WebEvent {
case back
case forward
}
let eventPublisher: AnyPublisher<WebEvent, Never>
init(eventPublisher: AnyPublisher<WebEvent, Never>) {
self.eventPublisher = eventPublisher
eventPublisher.sink { event in
// forward the appropriate event to your underlying WKWebView
}
}
}
Next, in your parent, create the PassthroughSubject
to create these events.
struct ParentView: View {
private let eventSender = PassthroughSubject<WebView.WebEvent, Never>()
var body: some View {
VStack {
Button("Back") {
self.eventSender.send(.back)
}
Button("Forward") {
self.eventSender.send(.forward)
}
WebView(eventPublisher: eventSender.eraseToAnyPublisher())
}
}
}