SwiftUI 中的变量更新时文本不更新(Swift 5,Xcode 13)

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

我有这个变量 timeRemaining,按下按钮时它应该从 timeRemaining 中减去一个。

我希望每当用户单击按钮时更新文本并认为这会起作用,但它没有更新。

     var timeRemaining: CGFloat = 4

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

     Text("Time: \(timeRemaining)")

我还尝试将 CGFloat 分配给另一个变量,然后将其设为整数。像这样:

var timeRemaining: CGFloat = 4

struct timeView {

@State private var timeRemaining: CGFloat = defaultTimeRemaining


var body: some View {

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

  }
}

有谁知道如何解决这个问题?提前致谢:)

确保您正在更新@State 变量。例如:

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")
        }

    }
}