Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get button text to change in SwiftUI when changing boolean value

I want to have a button that when clicked toggles a boolean and changes the text of the button. By using print statements I can confirm that the button is properly toggling the bool value but it is not changing the text of the button.

I have tried manually setting the bool default value to false and this does change the text but I am still unable to get it to change when toggled.

Button(action: {
                Variables.userTriangle.cupShooting = 7
                Variables.userTriangle.triangle[6].toggleStatus()
            }) {
                if !Variables.userTriangle.triangle[6].status {
                    Text("x")
                        .font(.largeTitle)
                } else {
                    Text("7")
                        .font(.largeTitle)
                }
            }

When the button it tapped, I expect it to change the value of the text by changing the boolean value. I plan on having multiple of these buttons.

like image 348
Thomas Braun Avatar asked Sep 09 '19 14:09

Thomas Braun


2 Answers

I believe the view is only built once and so it is not checking that if condition every time it changes...

What you can do is make your text a @State var and then when you change it it will update in the view automatically.

@State var someText = "x"

...

Button(action: {
                Variables.userTriangle.cupShooting = 7
                Variables.userTriangle.triangle[6].toggleStatus()
                if (Variables.userTriangle.triangle[6].status) {
                   self.someText = "7"
                } else {
                   self.someText = "x"
                }
            }) {
                Text(self.someText).font(.largeTitle)

            }

like image 71
Quinn Avatar answered Nov 15 '22 07:11

Quinn


The simpler way would be:

Button(action: {
            Variables.userTriangle.cupShooting = 7
            Variables.userTriangle.triangle[6].toggleStatus()
        }) {
            Text(Variables.userTriangle.triangle[6].status ? "7" : "x")
        }
like image 29
LuLuGaGa Avatar answered Nov 15 '22 07:11

LuLuGaGa