Swag Mand
Swag Mand

Reputation: 45

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"

Upvotes: 1

Views: 372

Answers (1)

davidev
davidev

Reputation: 8517

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)"))

Upvotes: 1

Related Questions