Reputation: 45
I have some variables that I need in several views and I want the user to be able to change these. These variables edit a link, so depending on for example what the longitude is the result is different. And the values I get from the link are displayed in a graph.
So I want the user to be able to enter their own value for the given variables(in the code below). I don't care if it is in the same view, or if consists of two views and the variables are passed to the view with the graphs.
The only important thing, is that the graph and the link refreshes when the user clicks a button, so that the right graph is displayed.
Another important thing, is that I need to be able to access the variables at top-level. This is my code until now, but it shows the error:
Cannot convert value of type 'string' to expected argument type 'Binding'
import SwiftUI
var month = "1"
var day = "1"
var year = "2020"
var latitude = "59.911232"
var longitude = "10.757933"
var offset = "1.0"
struct ContentView: View {
var body: some View {
GraphView()
TextField(text: latitude)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Upvotes: 1
Views: 506
Reputation: 258591
TextField
requires binding to some dynamic property source of truth. If you want to keep those values globally then wrap them into some shared instance of view model, like
final class Params: ObservableObject {
static let global = Params()
var month = "1"
var day = "1"
var year = "2020"
var latitude = "59.911232"
var longitude = "10.757933"
var offset = "1.0"
}
so now we are able to observe (and update, and bind to) those parameters from view
struct ContentView: View {
@ObservedObject var global = Params.global
var body: some View {
GraphView()
TextField(text: $global.latitude)
}
}
Upvotes: 5