In the SwiftUI, how could I create two separate instances of the same struct? The purpose for this, in my case, is the following: I have an application written in the SwiftUI consisting of a tab bar. Each tab shows a different webpage. When I create the tab bar, for each tab object, I am currently passing a URLrequest as an argument of a struct. However, I have had to make a new struct with nearly the same code verbatum for each webpage/tab I want. When I try to just use the same struct, all tabs show the same webpage due to the first line of the struct:
static var cache = [URL: WKWebView]()
However, if I remove the static keyword, I just unresolvable errors. How can I do this successfully?
Ok, here's my continuation for the requested example. Here's the struct which controls the webview.
struct WebView : UIViewRepresentable {
static var cache = [URL: WKWebView]()
let request: URLRequest
func makeUIView(context: Context) -> WKWebView {
guard let url = request.url else {fatalError()}
if let webView = WebView.cache[url] {
return webView
}
let webView = WKWebView()
WebView.cache[url] = webView
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
if uiView.url == nil {
uiView.load(request)
}
}
}
Now here's the contentview:
struct ContentView: View {
var body: some View {
TabView {
WebView(request: URLRequest(url: URL(string: "https://www.google.com")!)).edgesIgnoringSafeArea(.all).tabItem {
VStack {
Text("Google")
}
}
WebView(request: URLRequest(url: URL(string: "https://www.apple.com")!)).edgesIgnoringSafeArea(.all).tabItem {
VStack {
Text("Apple")
}
}
}
}
}
However, this would cause both tabs to always show the same page. I clearly want them to show the urls specified. How might I accomplish this?
Try the following:
struct ContentView: View {
var body: some View {
TabView {
webView(url: "https://www.google.com")
.edgesIgnoringSafeArea(.all)
.tabItem {
VStack {
Text("Google")
}
}
webView(url: "https://www.apple.com")
.edgesIgnoringSafeArea(.all)
.tabItem {
VStack {
Text("Apple")
}
}
}
}
func webView(url: String) -> some View {
WebView(request: URLRequest(url: URL(string: url)!))
}
}
Note: instead of force-unwrapping URL(string: url)!
you may want to provide a default url or a default view. Even if the site is valid it may not always be available.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.