简体   繁体   中英

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.

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)

            }

The simpler way would be:

Button(action: {
            Variables.userTriangle.cupShooting = 7
            Variables.userTriangle.triangle[6].toggleStatus()
        }) {
            Text(Variables.userTriangle.triangle[6].status ? "7" : "x")
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM