I want the user to be able to enter some text into a TextField in View 1, and then depending on what the user entered the returned html is different. So it is important that the "value" var is assigned before the loadData function is initialised.
So if the user enters 1 in the textfield the url will look like this:
"www.example.com/1"
and the output (what is displayed on the website) will for example be:
"This is link number 1"
And if the user enters 70 in the TextField the url will look like this:
"www.example.com/70"
And the ouput:
"This is link number 70"
I have this code, but I need to find a way, to assign a value var, with the TextField input.
View 1:
struct ContentView: View {
@EnvironmentObject var value1: ViewModel
var body: some View {
if value1.page == 0{
VStack{
TextField("", text: $value1.value)
Button(action:{ value1.page = 1}){
Text("To next view")
}.frame(width: 300, height: 100, alignment: .center)
}
} else {
TestView()
}
}
}
View2:
class ViewModel: ObservableObject {
@Published var value:String = ""
@Published var page = 0
}
struct TestView: View {
var url = URL(string: "www.example.com/(value)")
func loadData(from url: URL?) -> String {
guard let url = url else {
return "nil"
}
let html = try! String(contentsOf: url, encoding: String.Encoding.utf8)
return html
}
var body: some View {
VStack{
Text(loadData(from: url))
Button(action:{ ViewModel.init().page = 0}){
Text("To next view")
}
}.frame(width: 300, height: 100, alignment: .center)
}
}
And the ouput:
"This is link number 70"
question from:
https://stackoverflow.com/questions/65873329/how-do-i-pass-variables-between-views-in-swiftui 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…