[英]Separate Instances of Same Struct SwiftUI
In the SwiftUI, how could I create two separate instances of the same struct?在 SwiftUI 中,如何创建同一结构的两个单独实例? The purpose for this, in my case, is the following: I have an application written in the SwiftUI consisting of a tab bar.就我而言,这样做的目的如下:我有一个用 SwiftUI 编写的应用程序,它由一个标签栏组成。 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.当我创建标签栏时,对于每个标签 object,我当前将 URLrequest 作为结构的参数传递。 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.但是,如果我删除 static 关键字,我只是无法解决的错误。 How can I do this successfully?我怎样才能成功地做到这一点?
Ok, here's my continuation for the requested example.好的,这是我对所请求示例的继续。 Here's the struct which controls the webview.这是控制 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)!
注意:而不是强制解包URL(string: url)!
you may want to provide a default url or a default view.您可能需要提供默认 url 或默认视图。 Even if the site is valid it may not always be available.即使该站点是有效的,它也可能并不总是可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.