Reputation: 337
Basic questions again: I want to make the variable "anytext" visible and accessible for all future views I am going to add. In my case the variable is going to be a String.
import SwiftUI
struct Entry: View {
@State var anytext: String = ""
var body: some View {
VStack {
TextField("Enter text here", text: $anytext)
.padding()
.border(Color.black, width: 1)
.padding()
}
}
}
struct Entry_Previews: PreviewProvider {
static var previews: some View {
Entry()
}
}
Upvotes: 5
Views: 6595
Reputation: 30461
Create & pass in an environment object at the root view of your app, or where any 'children' views may need access to anytext
. Store anytext
as a @Published
property in that ObservedObject
.
That's a pointer, but there will be lots of similar questions and stuff. Here is a HWS article which may help.
Here is an example:
class MyModel: ObservableObject {
@Published var anytext = ""
}
struct ContentView: View {
@StateObject private var model = MyModel()
var body: some View {
Entry().environmentObject(model)
}
}
struct Entry: View {
@EnvironmentObject private var model: MyModel
var body: some View {
VStack {
TextField("Enter text here", text: $model.anytext)
.padding()
.border(Color.black, width: 1)
.padding()
TextDisplayer()
}
}
}
struct TextDisplayer: View {
@EnvironmentObject private var model: MyModel
var body: some View {
Text(model.anytext)
}
}
Result:
All three views have model
which they can access, to get the anytext
property.
To answer your questions:
You use @Published
because String
, Float
, Double
etc are all value types.
Using environment objects, as shown here.
They are not persisted, see @AppStorage
for saving that.
Upvotes: 9