[英]@State not updating SwiftUI
我对 Swift 和 SwiftUI 很陌生,所以这可能有一些我忽略的明确答案。 我的目标是每次单击按钮时都会更新此进度环。 我希望按钮将DailyGoalProgress
更新某个数字,这很有效。 但是,我还希望DailyGoalProgress
然后除以一个数字来生成这个@State
。 正如我所说,DailyGoalProgress 更新但@State
没有,我无法弄清楚我做错了什么。 任何帮助是极大的赞赏。 谢谢!
这是我的代码的缩写版本:
struct SummaryView: View {
@AppStorage ("DailyGoalProgress") var DailyGoalProgress: Int = 0
@State var progressValue: Float = 0 //This just stays at zero and never changes even with the button press
var body: some View {
ProgressBar(progress: self.$progressValue, DailyGoalProgress: self.$DailyGoalProgress)
}
}
这是另一种观点:
@Binding var DailyGoalProgress: Int
@Binding var progressValue: Float
var body: some View {
Button(action: {DailyGoalProgress += tokencount; progressValue = Float(DailyGoalProgress / 30)}) {
Text("Mark This Task As Completed")
.font(.title3)
.fontWeight(.semibold)
.foregroundColor(Color.white)
}
}.frame(width: 330.0, height: 65.0).padding(.bottom, 75.0)
Spacer()
}.padding(.top, 125.0)
}
Spacer()
}
}
}
您的问题是关于Int 到 Float , DailyGoalProgress是Int ,您应该先将其转换为Float然后将其除以 30.0,然后它会起作用。
它称为推理,Swift 想以自己的方式帮助你。 但这给你带来了麻烦。
如果您想详细了解会发生什么:当您将 DailyGoalProgress 除以 30 时,结果是什么,它将被视为 Int,那是什么意思? 0 到 1 之间的平均数总是 0,然后你给 Float 0,也没有任何反应!
import SwiftUI
struct ContentView: View {
@AppStorage ("DailyGoalProgress") var DailyGoalProgress: Int = 0
@State var progressValue: Float = 0
var body: some View {
Spacer()
Text(DailyGoalProgress.description)
Text(progressValue.description)
ProgressBar(DailyGoalProgress: $DailyGoalProgress, progressValue: $progressValue)
Spacer()
}
}
struct ProgressBar: View {
@Binding var DailyGoalProgress: Int
@Binding var progressValue: Float
let tokencount: Int = 30 // <<: Here for example I used 30
var body: some View {
Button(action: {
DailyGoalProgress += tokencount
progressValue = Float(DailyGoalProgress)/30.0 // <<: Here
}, label: {
Text("Mark This Task As Completed")
.font(.title3)
.fontWeight(.semibold)
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.