If View2
is being used in View1
you could do something like this:
View1:
struct FirstView: View {
@State var count = 0
var body: some View {
VStack{
Text("\(self.count)")
Button(action:
{self.count = self.count-10})
{
Text("-")
}
SecondView(count: self.$count)
}
}
}
And View2:
struct SecondView: View {
@Binding var count: Int
var body: some View {
Button(action: {self.count = 0}) {
Text("Reset")
}
}
}
Edit
If they are completely different views and need single source of truth you could use an observableObject/EnvironmentVariables. The best way would be to add the environment variable to the ContentView
where it's first defined in the SceneDelegate
ContentView().environmentObject(SourceOfTruth())
Here is SourceOfTruth:
class SourceOfTruth: ObservableObject{
@Published var count = 0
}
Then you could use EnvironmentObjects to the other views:
Here is ContentView
:
struct ContentView: View {
@EnvironmentObject var truth: SourceOfTruth
var body: some View {
VStack {
FirstView()
SecondView()
}
}
}
Here is FirstView
:
struct FirstView: View {
@EnvironmentObject var truth: SourceOfTruth
var body: some View {
VStack{
Text("\(self.truth.count)")
Button(action:
{self.truth.count = self.truth.count-10})
{
Text("-")
}
}
}
}
Here is SecondView
:
struct SecondView: View {
@EnvironmentObject var truth: SourceOfTruth
var body: some View {
Button(action: {self.truth.count = 0}) {
Text("Reset")
}
}
}