Yonus
Yonus

Reputation: 233

How can I change a global variable's value from inside a function?

I have a @State boolean in my code inside the struct which I have a button that toggle()s it. However, I want to use that variable in my other views as well. So I need to have it outside struct so I can use it another place. My question is that how can I now change its value? Previously my button's action toggled it. How can I change it now?

Here is my code:

struct ContentView: View {
    @State var checked: Bool = false
    var body: some View {
     HStack {
            Button(action: {checked.toggle()}) {
                Image(systemName: checked ? "checkmark.square": "square")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .scaledToFit()
                .foregroundColor(.black)
                .frame(height: 20)
            }
            Text("I agree")
            .fontWeight(.bold)
            Spacer()
        }
        .padding(.horizontal, 20)
    }
}

However, I want this to work:

var checked:Bool = false
struct ContentView: View {
    var body: some View {
     HStack {
            Button(action: {checked.toggle()}) {
                Image(systemName: checked ? "checkmark.square": "square")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .scaledToFit()
                .foregroundColor(.black)
                .frame(height: 20)
            }
            Text("I agree")
            .fontWeight(.bold)
            Spacer()
        }
        .padding(.horizontal, 20)
    }
}

Upvotes: 3

Views: 726

Answers (1)

Asperi
Asperi

Reputation: 257719

The possible solution is to use shared observable object with wrapped this property, then it can be observed in all dependent views.

Here is a demo. Tested with Xcode 12.1 / iOS 14.1

class GlobalState: ObservableObject {
    static let shared = GlobalState()
    
    @Published var checked:Bool = false
}

struct myView: View {
    @ObservedObject var gs = GlobalState.shared
    
    var body: some View {
        HStack {
            Button(action: {gs.checked.toggle()}) {
                Image(systemName: gs.checked ? "checkmark.square": "square")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .scaledToFit()
                    .foregroundColor(.black)
                    .frame(height: 20)
            }
            Text("I agree")
                .fontWeight(.bold)
            Spacer()
        }
        .padding(.horizontal, 20)
        Spacer()
    }
}

Upvotes: 3

Related Questions