Search code examples
iosswiftuistepper

Prevent UIStepper from being 0?


I have a UIStepper that has a stepValue of 1. I would like the UIStepper to be able to be positive or negative up until its maximum and minimum values, but never 0.

Every attempt I have made at solving this is unable to account for whether the stepper was decreasing or increasing (thus should skip 0 to 1 or to -1). The only other thing I can think of is saving the previous value and comparing, but that sounds a little involved for such a simple task.

Any ideas? Has anyone else ran into the same requirements?


Solution

  • I would approach this from a different direction. Let the stepper do what it does, and just change your interpretation of it.

    For example, if you have a stepper that you want to go from -5 to +5 but skipping 0:

    1. Set stepper minumum to -5.
    2. Set stepper maximum to 4.
    3. Set stepper stepValue to 1.
    4. When you read the stepper value, add 1 if value is non-negative:

      let value = stepper.value + (stepper.value < 0 ? 0 : 1)
      
    5. When you set the stepper value, first lower the positive values by 1:

      // value of 3 will be represented in the stepper by 2
      value = 3
      stepper.value = value - (value > 0 ? 1 : 0)
      

    Hide the details with a nonZeroValue computed property

    You can hide these +1 and -1 adjustments by creating an extension to UIStepper that adds a new computed property called nonZeroValue.

    extension UIStepper {
        var nonZeroValue: Double {
            get {
                return self.value + (self.value < 0 ? 0 : 1)
            }
            set {
                self.value = newValue - (newValue < 0 ? 0 : 1)
            }
        }
    }
    

    Then, just use stepper.nonZeroValue in place of stepper.value in your code.