Search code examples
iosios5uicontroluicontroleventsuistepper

Modify UIStepper autorepeat behaviour


I have a client who wants me to modify a UIStepper's autorepeat behaviour.

If the user selects touches and holds say the + button of the stepper, the value of the stepper starts increasing at a rate of 1 every half second or so, and then after about 3 seconds, the values start changing much more rapidly.

Is there anyway to modify how this works, so that, for example, the values will increase at the faster rate immediately if the user taps and holds?

I've looked at the UIStepped documentation and I didn't see anything regarding this, but I wondered if there was a way to do this through an IBAction or something.


Solution

  • First, add two actions for your stepper:

    [theStepper addTarget:self action:@selector(stepperTapped:) forControlEvents:UIControlEventTouchDown];
    [theStepper addTarget:self action:@selector(stepperValueChanged:) forControlEvents:UIControlEventValueChanged];
    

    Here's what those actions look like:

    - (IBAction)stepperTapped:(id)sender {
    self.myStepper.stepValue = 1;
    self.myStartTime = CFAbsoluteTimeGetCurrent();
    

    }

    - (IBAction)stepperValueChanged:(id)sender {
    self.myStepper.stepValue = [self stepValueForTimeSince:self.myStepperStartTime];
    // handle the value change here
    

    }

    Here's the magic code:

    - (double)stepValueForTimeSince:(CFAbsoluteTime)aStartTime {
    double theStepValue = 1;
    CFAbsoluteTime  theElapsedTime  = CFAbsoluteTimeGetCurrent() - aStartTime;
    
    if (theElapsedTime > 6.0) {
        theStepValue = 1000;
    } else if (theElapsedTime > 4.0) {
        theStepValue = 100;
    } else if (theElapsedTime > 2.0) {
        theStepValue = 10;
    }
    
    return theStepValue;
    

    }