I’m trying to create a Global Binding Date that I can use across multiple areas of my App.
Essentially, I want to allow the use to change ‘todays date’ to any future date and update the rest of my app accordingly.
I’ve tried creating a GlobalVariables class in a Swift file, but getting a bit lost as to how to create the variable correctly (the below code errors)
class GlobalVariables: ObservableObject {
@Binding var myDate: Date = Date()
}
I want to then use a DatePicker in another View to update the myDate variable, which will then update the other bits of my App.
Thanks
>Solution :
You should use @Published property wrapper. This way it will publish any changes and update the UI accordingly.
class GlobalVariables: ObservableObject {
@Published var myDate = Date()
}
You also need to inject the same instance of your GlobalVariables in order to sync all views. You can use environment object or dependency injection with other methods.
struct MainView: View {
@StateObject globalVariables = GlobalVariables()
var body: some View {
VStack {
FirstView()
.environmentObject(globalVariables)
SecondView()
.environmentObject(globalVariables)
}
}
}
struct FirstView: View {
@EnvironmentObject globalVariables: GlobalVariables
var body: some View {
DatePicker("", selection: $globalVariables.myDate)
}
}
struct SecondView: View {
@EnvironmentObject globalVariables: GlobalVariables
var body: some View {
DatePicker("", selection: $globalVariables.myDate)
}
}