Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI ProgressView is not updating progress value within Button closure

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

like image 673
Gurkenkr4ll3 Avatar asked Feb 23 '26 18:02

Gurkenkr4ll3


1 Answers

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).

like image 168
Alexander Sandberg Avatar answered Feb 26 '26 09:02

Alexander Sandberg