0

My goal is to create a UIProgressView that shows the progress that the user enters in. I have been looking for examples everywhere and all of them use the progress view with a timer. I also want the progress to be saved using User Defaults. Is there a way to do it where the user enters in the values? If so, can anyone point me in the right direction?

    progressView.progress = (sender as AnyObject).value
rmaddy
  • 314,917
  • 42
  • 532
  • 579
N.Lucas
  • 11
  • 1
  • 3

2 Answers2

0

You can try adding a computedProperty like this in your viewController:

var progress: Float? {
    set{
        guard let value = newValue else {
            UserDefaults.standard.removeObject(forKey: "progress")
            UserDefaults.standard.synchronize()
            progressView.progress = 0
            return
        }
        progressView.progress = value
        UserDefaults.standard.set(value, forKey: "progress")
        UserDefaults.standard.synchronize()
    }
    get{
        return UserDefaults.standard.float(forKey: "progress") ?? 0.0
    }
}

When you want to set the saved progress you can do:

progressView.progress = self.progress

When you want to set it from a textField:

self.progress = (Float(textField.text ?? "") ?? 0.0)/100

This way you are saving it in UserDefalts also

Agent Smith
  • 2,873
  • 17
  • 32
0

UIProgressView.progress expects a Float value between 0.0 and 1.0.

You have to convert your UITextField string value to a Float value, like so:

let textField = sender as? UITextField
if let value = Float(textField?.text ?? ""), value >= 0 && value <= 1.0 {
    progressView.progress = value
}

If you expect a value between 0-100 in textField, use this instead:

if let value = Int(textField?.text ?? ""), (0...100).contains(value) {
    progressView.progress = Float(value / 100)
}

To save value to UserDefaults, use this:

UserDefaults.standard.removeObject(forKey: "progressValue")
UserDefaults.standard.synchronize()

And retrieve from UserDefaults:

let value = UserDefaults.standard.float(forKey: "progressValue") ?? 0
AamirR
  • 11,672
  • 4
  • 59
  • 73