SwiftUI webview 未使用@State 变量更新
SwiftUI webview not updating with @State variable
出于某种原因,我用来更新 WebView url 的 @State 变量没有更新。这两个按钮都会导致 'www.target.com' url.
import SwiftUI
struct ContentView: View {
var siteArray = ["http://www.google.com","http://www.yahoo.com","http://www.amazon.com"]
@State private var siteUrl = "http://www.target.com"
@State private var showWebView = false
var body: some View {
ScrollView{
Text("Websites")
Button("Target") {
showWebView.toggle()
}
Button("Google") {
siteUrl = siteArray[0]
showWebView.toggle()
}
}
.sheet(isPresented: $showWebView) {
WebView(url: URL(string: "\(siteUrl)")!)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
如有任何帮助,我们将不胜感激。谢谢!
尝试使用@Binding
例如:
struct WebView: View {
@Binding var siteUrl :String
var body: some View {
Text(siteUrl)
}
}
struct ContentView: View {
var siteArray = ["http://www.google.com","http://www.yahoo.com","http://www.amazon.com"]
@State private var siteUrl = "http://www.target.com"
@State private var showWebView = false
var body: some View {
ScrollView{
Text("Websites")
Button("Target") {
showWebView.toggle()
}
Button("Google") {
siteUrl = siteArray[1]
showWebView.toggle()
}
}
.sheet(isPresented: $showWebView) {
WebView(siteUrl: $siteUrl)
}
}
}
出于某种原因,我用来更新 WebView url 的 @State 变量没有更新。这两个按钮都会导致 'www.target.com' url.
import SwiftUI
struct ContentView: View {
var siteArray = ["http://www.google.com","http://www.yahoo.com","http://www.amazon.com"]
@State private var siteUrl = "http://www.target.com"
@State private var showWebView = false
var body: some View {
ScrollView{
Text("Websites")
Button("Target") {
showWebView.toggle()
}
Button("Google") {
siteUrl = siteArray[0]
showWebView.toggle()
}
}
.sheet(isPresented: $showWebView) {
WebView(url: URL(string: "\(siteUrl)")!)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
如有任何帮助,我们将不胜感激。谢谢!
尝试使用@Binding 例如:
struct WebView: View {
@Binding var siteUrl :String
var body: some View {
Text(siteUrl)
}
}
struct ContentView: View {
var siteArray = ["http://www.google.com","http://www.yahoo.com","http://www.amazon.com"]
@State private var siteUrl = "http://www.target.com"
@State private var showWebView = false
var body: some View {
ScrollView{
Text("Websites")
Button("Target") {
showWebView.toggle()
}
Button("Google") {
siteUrl = siteArray[1]
showWebView.toggle()
}
}
.sheet(isPresented: $showWebView) {
WebView(siteUrl: $siteUrl)
}
}
}