我是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,DailyGoalProgressInt是你应该把它转换成Float先把它除以30.0,然后就可以了。
它叫推理!Swift想用它自己的方式帮助你,但它却给你制造麻烦。
如果你想要详细说明发生了什么:当你把DailyGoalProgress除以30时,无论结果是什么,它都会被作为Int,那么这意味着什么?0到1之间的平均值总是0,然后你把0赋给Float,什么也没发生!
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)
})
}
}