Reputation: 71
I'm pretty new to Swift and SwiftUI, so this might have some clear answers that I'm overlooking. My goal is to have this progress ring update every time a button is clicked. I want the button to update DailyGoalProgress
by a certain number, and that works. However, I also want DailyGoalProgress
to then be divided by a number to make this @State
. As I said, the DailyGoalProgress updates but the @State
does not and I can't figure out what I'm doing wrong. Any help is greatly appreciated. Thanks!
Here is an abbreviated version of my code:
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)
}
}
Here is another view:
@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()
}
}
}
Upvotes: 1
Views: 429
Reputation: 1
Your problem is about Int to Float, DailyGoalProgress is Int and you should convert it to Float first then divid it to 30.0, then it will work.
It called Inference! Swift wants help you in its own way, but it makes problem to you.
if you want detail what happens: when you divid DailyGoalProgress to 30 what ever the result is it will taken as Int, then what does mean? that mean number between 0 to 1 became always 0, then you gave 0 to Float and also nothing happens!
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)
})
}
}
Upvotes: 2