Search code examples
iosobjective-cuislider

How to fire a method when UISlider stops?


I've got a UISlider that allows the user to changes values. I want a UILabel to continuously update as the slider moves from left to right.

So, I wrote my UISlider method like this:

    - (IBAction)yearsSlider:(UISlider *)sender
{
    self.yearsLabel = [NSString stringWithFormat:@"%.0f", sender.value];

}

This works just fine. I need to fire a different method when the user stops the slider.

I thought about using NSTimer for this - so rewrote the above method like so:

     - (IBAction)yearsSlider:(UISlider *)sender
    {
        self.yearsLabel = [NSString stringWithFormat:@"%.0f", sender.value];

 if (!self.timer){
        self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(requestCalculation) userInfo:nil repeats:NO];] 
    }

    }

Then in the requestCalculation method I invalidate the timer and set it to nil = like so:

 [self.timer invalidate];
self.timer = nil;

This slows it down - but the method is called while the slider is moving. Which is not what I want.

I am aware that I can use self.mySlider.continuous = NO; which means the target method is only fired once when the user lifts their finger off the slider. The problem with this is my UILabels are not updated as the user sliders their left and right on the slider.


Solution

  • You have the right idea. But you are canceling the timer in the wrong method. You want to cancel the (previous) timer in the yearsSlider: method, not the requestCalculation method.

    - (IBAction)yearsSlider:(UISlider *)sender {
        // Cancel the current timer
        [self.timer invalidate];
    
        self.yearsLabel = [NSString stringWithFormat:@"%.0f", sender.value];
    
        // Start a new timer in case this is the last slider value
        self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(requestCalculation) userInfo:nil repeats:NO];
    }
    

    BTW - two seconds seems to be a rather long delay for this check. Something smaller would probably be better.

    Do not invalidate the timer in requestCalculation. Just set it to nil.

    FYI - Use NSNumberFormatter to convert the slider value to a user displayed value. Doing this will ensure the value is formatted properly for the user's locale.