12

The value of the UISlider currently shows as a float. How do I show it as an integer?

sliderCtl = [[UISlider alloc] initWithFrame:frame];
    sliderCtl.minimumValue = 1;
    sliderCtl.maximumValue = 15;
    sliderCtl.continuous = NO;
    sliderCtl.value = 1;
    [sliderCtl setShowValue:YES];
Brian
  • 14,610
  • 7
  • 35
  • 43
RAGOpoR
  • 8,118
  • 19
  • 64
  • 97

2 Answers2

23

if you want your slider to snap to different integer values, you could use something like this in your valueChanged-function:

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

This will snap the slider after releasing your finger to values like 1,2,...,15 based on the distance between two numbers. If for instance you released the slider at 2.4, it'll snap back to 2, whereas at 2.6 it would snap to 3.

gchbib
  • 1,955
  • 1
  • 17
  • 23
  • 1
    roundtl doesn't appear to exist in iOS. Xcode then brilliantly suggests "roundl", which doesn't exist either. – Oscar Oct 06 '11 at 00:24
  • Thanks for the heads-up. I've updated my answer accordingly to use the function roundl(), which I just tested. The weird thing is, my previous answer worked at that time... – gchbib Oct 08 '11 at 19:51
  • Looks like this works again as of Xcode 4.5 - I've got it working properly, only change is it will snap as the user is still using it - the thumb won't move until the user drags it to the next value. – GeneralMike Nov 29 '12 at 18:35
  • Little correction: int discreteValue = roundl([(UISlider*)sender value]); – mafonya Dec 17 '13 at 21:46
  • No need for the UISlider-cast in this case since it's already set as the sender-parameter's type of the IBAction. Would make sense if the type was "id" though ;-) – gchbib Mar 01 '14 at 17:32
3

You could truncate or round the value from the slider and then update it to give the user feedback about the change (it would appear to snap to the integer value when the user releases).

gerry3
  • 21,420
  • 9
  • 66
  • 74