Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISlider with increments of 5

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

like image 463
Tyler29294 Avatar asked Mar 25 '10 21:03

Tyler29294


3 Answers

A slightly more elegant solution in Swift could be something like this

let step: Float = 5
@IBAction func sliderValueChanged(sender: UISlider) {
  let roundedValue = round(sender.value / step) * step
  sender.value = roundedValue
  // Do something else with the value

}

This way you get steps of 5. You can read more about the setup in my post.

like image 40
Jure Avatar answered Nov 20 '22 23:11

Jure


Add a target like this:

slider.continuous = YES;
[slider addTarget:self
      action:@selector(valueChanged:) 
      forControlEvents:UIControlEventValueChanged];

And in the valueChanged function set the value to the closest value that is divisible by 5.

[slider setValue:((int)((slider.value + 2.5) / 5) * 5) animated:NO];

So if you need any interval other than 5 simply set it like so:

float interval = 5.0f;//set this
[slider setValue:interval*floorf((slider.value/interval)+0.5f) animated:NO];
like image 166
Tuomas Pelkonen Avatar answered Nov 20 '22 22:11

Tuomas Pelkonen


There is another way to active the stepper functionality. works in a general case

Example:

range of data is 0 - 2800 and I want the increments to be in 25 unit values. I would do the following

  1. set up the range of the slider to be 0 - (maxRange/unitsteps).
  2. when the value changed method runs use (int)slider.value * unitsteps .

in the example above my slider would be set in IB to range 0 - 112. and my code would be (int)slider.value * 25.

if you then have a text field that can be modified for direct input you would just do the opposite set the slider value to the [textfield.text intValue]/ unitsteps.

like image 10
MB. Avatar answered Nov 20 '22 23:11

MB.