Home > Blockchain >  SwiftUI TabView with shared content view across multiple tabs
SwiftUI TabView with shared content view across multiple tabs

Time:05-30

I am building an application that is based around WKWebView but uses some native elements. I am looking to add tabs to it and I reached for TabView, but the problem I am facing is that for each tab, I need to have a new instance of WKWebView:

TabView(selection: $tab) {
    ForEach(tabs, id: \.0) { (tag, name, icon) in
        MyWebView()
            .tabItem {
                Image(systemName: icon)
                Text(name)
            }
            .tag(tag)
    }
}
.onChange(of: tab) { tab in
    // postMessage to the WKWebView
}

This makes it so that each tab has its own WKWebView instance and whenever I tap on a tab, it sends a message to the associated web view.

I would however prefer to have a single WKWebView and somehow wire up the TabView such that it would show that same single WKWebView for each tab so that I could just send a message to the sole WKWebView instructing it to switch to the web view appropriate for the current tab.

Is this possible? Can I perhaps create a row of tabs like this without using TabView so that I could stack the sole WKWebView on top of this row?

CodePudding user response:

It is possible to have single static instance of WKWebView in representable, everything else depends on app logic

struct MyWebView: UIViewRepresentable {
    static let nativeWebView = WKWebView()     // << here !!

    func makeUIView(context: Context) -> some UIView {
        Self.nativeWebView                     // << here !!
    }

    func updateUIView(_ uiView: UIViewType, context: Context) {
    }
}
  • Related