Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - How do I create Global @State Variables?

Tags:

swiftui

Is it possible to create a global @State variable in SwiftUI that can be accessed across multiple Swift UI files?

I've looked into @EnvironmentObject variables but can't seem to make them do what I want them to do.

like image 468
hudson Avatar asked Jul 16 '19 20:07

hudson


1 Answers

As of Beta 3 you cannot create a top-level global @State variable. The compiler will segfault. You can place one in a struct and create an instance of the struct in order to build. However, if you actually instantiate that you'll get a runtime error like: Accessing State<Bool> outside View.body.

Probably what you're looking for is an easy way to create a binding to properties on a BindableObject. There's a good example of that in this gist.

It is possible to create a Binding to a global variable, but unfortunately this still won't do what you want. The value will update, but your views will not refresh (code example below).

Example of creating a Binding programmatically:

var globalBool: Bool = false {
    didSet {
        // This will get called
        NSLog("Did Set" + globalBool.description)
    }
}

struct GlobalUser : View {

    @Binding var bool: Bool

    var body: some View {
        VStack {
            Text("State: \(self.bool.description)") // This will never update
            Button("Toggle") { self.bool.toggle() }
        }
    }
}

...
static var previews: some View {
    GlobalUser(bool: Binding<Bool>(getValue: { globalBool }, setValue: { globalBool = $0 }))
}
...
like image 129
arsenius Avatar answered Nov 13 '22 09:11

arsenius