Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI: Global Binding Date Variable

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading