Here is a standalone program that shows my problem. When the user clicks on the "Save Report" button, I expect the button label to update through:
The @State var is init'ed to showProgressView: Bool = false
When set to true (or via .toggle()), there is no change the button label view (Should show the ProgressView())
I've messed up somewhere, or do not understand the @State/@Binding interaction.
//
// ContentView.swift
// state-test
import SwiftUI
enum UploadJsonFileStatus {
case success, failedToUpload, failedToRemove
}
struct ContentView: View {
// Form support
@State private var formValid: Bool = false
@State private var submitted: Bool = false
@State private var showProgressView: Bool = false
@State private var jsonFilesProgress: Double = 0.0
var body: some View {
var jsonFiles = [URL]()
var jsonFilesTotal: Double = 1.0
NavigationView {
Form {
// Submit form
Section(header: Text("Submit")) {
Button(action: {
// Get array if JSON file URLs
jsonFiles = getJsonFileURLs()
jsonFilesTotal = Double(jsonFiles.count)
// Set up @State var
jsonFilesProgress = 0.0
showProgressView = true // Turn on
// Walk through files, attempt to upload
for (i, jsonFileURL) in jsonFiles.enumerated() {
jsonFilesProgress = Double(i) // Update @State var
let xferStatus = uploadJsonFile(jsonFileURL: jsonFileURL)
print("\(xferStatus)")
}
// Update @State var
showProgressView = false // Turn off
submitted = true // Turn on
}, label: {
SubmitInformationView(submitted: $submitted,
showProgressView: $showProgressView,
jsonFilesProgress: $jsonFilesProgress,
jsonFilesTotal: jsonFilesTotal)
}) // Button
} // Section Submit
} // form
} // nav
} // body
} // struct
struct SubmitInformationView : View {
@Binding var submitted: Bool
@Binding var showProgressView: Bool
@Binding var jsonFilesProgress: Double
var jsonFilesTotal: Double
var body: some View {
HStack {
Spacer()
if submitted {
Text("Reports uploaded").foregroundColor(.green)
} else {
if showProgressView {
ProgressView("Uploading \(Int(jsonFilesProgress))...", value: jsonFilesProgress, total: jsonFilesTotal)
} else {
Text("Save Report")
}
}
Spacer()
} // hstack
} // body
} // struct
// Return an array of URLs
func getJsonFileURLs() -> Array<URL> {
let fileURLs = [URL(string: "file1.json")!, URL(string: "file2.json")!, URL(string: "file3.json")!, URL(string: "file4.json")!]
return fileURLs
}
// Upload one URL
func uploadJsonFile(jsonFileURL: URL) -> UploadJsonFileStatus {
print("Uploading file \(jsonFileURL.lastPathComponent)")
sleep(2)
return UploadJsonFileStatus.success
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}