lundi 30 novembre 2020

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 myView: 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)
                            Spacer()
}
}

However, I want this to work:

var checked:Bool = false
struct myView: 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)
                            Spacer()
}
}

Aucun commentaire:

Enregistrer un commentaire