SwiftUI ProgressView is not updating progress value within Button closure

1.4k Views Asked by At

It’s a rather simple example I am creating in Swift Playgrounds on iPad, but I had the same problem in a larger Xcode project. I try to update the progress view whenever I click on the button in order to show the user how many (in this case) names are left in the data. However the progress view just does not want to update. Any suggestions?

import SwiftUI

struct ContentView: View {

let names = ["Tim", "Peter", "Jennifer", "Wolfgang"]
@State private var index = 0
@State private var progress = 0.0
var body: some View {
    VStack(spacing: 50) {
        Text(names[index])
                .font(.title)
        ProgressView(value: progress)
            .progressViewStyle(.linear)
            .padding(.horizontal)
        Button("Next") {
            if index < names.count - 1 {
                index += 1
                progress += Double(1 / names.count)
            } else {
                index = 0
            }
        }
        
    }
}

}

Thanks in advance

1

There are 1 best solutions below

0
Alexander Sandberg On BEST ANSWER

Your progress is always 0 because Double(1 / names.count) always returns 0. You have to convert names.count to a Double before dividing by 1.

Solution

Try progress += 1 / Double(names.count).