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.
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 }))
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With