Search code examples
iosswiftuistepper

Increment UIStepper Value based on minute, hour, day etc. SWIFT


I am currently trying to increment a uistepper and change its value based on its current value. The uistepper is supposed to act as a time keeper. It increments by 5 minutes until it reaches 60 minutes, where it then increments by 60 minutes. Once it reaches 120 minutes, I want the stepper to increment by 1440 minutes which is 1 day. My code is having issues, however, and another problem I'm running into is decrementing the stepper so that you can go from a day back down to an hour and then back down to minutes.

This is my code right now:

func stepperValueChanged(stepper: UIStepper) {
    var value = Int(stepper.value)
    stepper.minimumValue = 0
    if (stepper.value != 0 && stepper.value <= 60) {
        stepper.stepValue = 5
        stepper.value -= 5
        stepper.value += 5
        value = Int(stepper.value)
        reminderSubLabel.text = "\(value) minutes before"
        if stepper.value == 60 {
        reminderSubLabel.text = "\(value / 60) hour before"
        }
    } else if stepper.value >= 60 && stepper.value <= 180 {
        if stepper.value == 60 {
            reminderSubLabel.text = "\(value / 60) hour before"
            stepper.value -= 5
            stepper.value += 60
        } else {
        //stepper.value = 120
        value = Int(stepper.value / 60)
        stepper.stepValue = 60
        stepper.value -= 60
        stepper.value += 60
        reminderSubLabel.text = "\(value) hours before"
        }
        if stepper.value == 120 {
            stepper.value = 1440
            stepper.value -= 1320
            stepper.value += 1440
            //stepper.stepValue = 1320
        }
    }
    if stepper.value == 0 {
        stepper.stepValue = 5
        stepper.value = 0
        reminderSubLabel.text = "At the time of the event"

    }
    stepper.minimumValue = 0
    stepper.maximumValue = 20160
    print("\(stepper.value)")
}

Solution

  • You should not bind to the value property of UIStepper. Try use sort of abstraction where value of stepper is x and value you need in minutes is y. All you need is to implement y = f(x) in stepperValueChanged(stepper:). It's pretty simple if step is 1.

    var minutes = 0
    
    @IBAction func stepperValueChanged(_ stepper: UIStepper) {
        let value = Int(stepper.value)
        var minutes = 0
        for step in 0..<value {
            if step <= 11 {
                minutes += 5
            } else if step <= 12 {
                minutes += 60
            } else {
                minutes += 1440
            }
        }
        self.minutes = minutes
    }