Increment UISlider by 1 in range 1 to 100

21,948

Solution 1

you could try this:

float RoundValue(UISlider * slider) {
  return roundf(slider.value * 2.0) * 1;
}

Solution 2

//Only generate update events on release
slider.continuous = NO;

//Round the value and set the slider
- (IBAction)sliderChange:(id)sender
{
    int rounded = sender.value;  //Casting to an int will truncate, round down
    [sender setValue:rounded animated:NO];

    NSLog(@"%f", sender.value);
}

Solution 3

yourSlider.minimumValue = 1;
yourSlider.maximumValue = 100;
[yourSlider addTarget:self action:@selector(roundValue) forControlEvents:UIControlEventValueChanged];

- (void)roundValue{
    yourSlider.value = round(yourSlider.value);
}

also see this bellow answer helpful toy you,give some idea...

UISlider increments

and also another which may give you some idea..

UISlider with increments of 5

Solution 4

I know i'm late to the party but I've also had to do this recently. Here is how I've done it in swift using XCode 8.3.2:

    @IBAction func sliderValueChanged(_ slider: UISlider) {
    label.text = Int(slider.value)
}

Simples! I know I could have used 'Any' instead of 'UISlider', but I think this makes my intention clearer ;)

Solution 5

change

` NSLog(@"slider.value=%f",slider.value);`

to

 NSLog(@"slider.value=%.f",slider.value); 

if you want one digit then :

 NSLog(@"slider.value=%.0f",slider.value);

but this will give you results like 1.0,1.1,....

Share:
21,948
Krunal
Author by

Krunal

iPhone/iPad developer from Mumbai (India) and you will always find me here to help you ;)

Updated on December 27, 2020

Comments

  • Krunal
    Krunal over 3 years

    I am new to iPhone,

    How do I have my UISlider go from 1 to 100 in increments of 1?

        slider = [[UISlider alloc] init];
        [slider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
        [slider setBackgroundColor:[UIColor clearColor]];
        slider.minimumValue = 1;
        slider.maximumValue = 100;
        slider.continuous = YES;
        slider.value = 0.0;
    
    - (IBAction)sliderChange:(id)sender{
        NSLog(@"slider.value=%f",slider.value);
    }
    

    When i slide my log shows...

    slider.value = 1.000000
    slider.value = 1.123440
    slider.value = 1.234550
    slider.value = 1.345670
    slider.value = 1.567890
    .
    .
    .
    

    I want slider value as 1.0 , 2.0 , 3.0 and so on...

    • Kamleshwar
      Kamleshwar over 11 years
      -(IBAction)valueChanged:(UISlider*)sender { int discreteValue = roundl([sender value]); // Rounds float to an integer [sender setValue:(float)discreteValue]; // Sets your slider to this value }