UISlider increments

2020-07-30 00:05发布

问题:

I have a UISlider that slides with a range from 0.0 to 1.0.

Out of the box, the slider lets users slide with a really high number of fraction digits, but I only want my users to be able to increment/decrement by .001 for each "tick" up or down of the slider.

Is this possible to set up?

Thank you!

回答1:

How big is this slider? Even if you've got it spanning the full width of the screen in landscape mode, a change of 0.001 is only about half a pixel. It sounds like you just need to round the slider's value (behind the scenes) to the precision you're after.



回答2:

What about something extremely simple, for example: A 3 choices slider (with values {0, 1, 2}), with a IBAction and a IBOutlet connected to it.

-(float)roundValue:(float)value{

    if(value <=   0.5) return 0;
    if(value <=   1.5) return 1;
    return 2;
}

-(IBAction)mySliderChanged:(id)sender {

    float value = mySliderOutlet.value; // retrieve value via IBOutlet
    value = [self roundValue:value];

    // Update the slider to 'snap' in final position
    [[self mySliderOutlet] setValue:value animated:YES];
}


回答3:

This should do the trick:

- (void) getSliderValue:(UISlider *)paramSender{
    float increment = 0.001;
    float newValue = paramSender.value /increment;
    paramSender.value = floor(newValue) * increment;
    NSLog(@"Current value of slider is %f", paramSender.value);
}