What's the idiomatic way to control a nested UIView in SwiftUI

前端 未结 1 1039
再見小時候
再見小時候 2021-01-07 01:53

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

相关标签:
1条回答
  • 2021-01-07 02:08

    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())
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题