Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

ios - How do I pass variables between views in swiftui?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could pass the URL directly to the TestView like this. Declare URL as parameter in TestView..

struct TestView: View {
    
    var url: URL?

And pass it like this

TestView(url: URL(string: "www.example.com/(value1.value)"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...