Search code examples
swiftxcodeswiftuiswift5xcode13

Text not updating when variable updates in SwiftUI (Swift 5, Xcode 13)


I have this variable, timeRemaining and when a button is pressed it should subtract one from timeRemaining.

I want the Text to update whenever the user clicks the button and thought this would work, but it doesn't update.

     var timeRemaining: CGFloat = 4

     Button {
                {
                    if (timeRemaining) >= 2 {
                        
                        timeRemaining -= 1
                        
                    }else if timeRemaining <= 1 {
                        
                        timeRemaining += 3
                        
                    }
                }()
            } label: {
                Image(systemName: "minus")
            }

     Text("Time: \(timeRemaining)")

I also tried assigning the CGFloat to another variable and then making that an integer. Like this:

var timeRemaining: CGFloat = 4

struct timeView {

@State private var timeRemaining: CGFloat = defaultTimeRemaining


var body: some View {

   Text("Time: \(Int(defaultTimeRemaining))")

  }
}

Does anyone know how to fix the problem? Thanks in advance :)


Solution

  • Make sure you are updating the @State variable. For example:

    struct ContentView: View {
        @State private var timeRemaining: Int = 0
        var body: some View {
            VStack {
                Text("Time \(timeRemaining)")
                ButtonView(timeRemaining: $timeRemaining)
            }
        }
    }
    
    struct ButtonView: View {
        @Binding var timeRemaining: Int
        var body: some View {
            Button {
                timeRemaining += 1
            } label: {
                Text("More time")
            }
    
        }
    }