-1

I am using a UISlider to allow a user to choose among four options. I ask the user a question of the form "how much do you like this thing?", they respond by moving the slider, and then behind the scenes I map the value of the slider to one of four elements of an array. I want the first quarter of the slider to correspond to the first element of the array, the second quarter of the slider to correspond to the second element of the array, and so on.

By default, the range of a slider is [0,1], so one natural way to do what I want is:

    let index = Int(rangedSlider.value * Float(currentAnswers.count) )

assuming that rangedSlider is the name of the outlet connected to the UISlider in question, and currentAnswers is the array of answers I'm mapping to. The issue with this is that if the user moves the slider all the way to the right, that sets the value of the slider to 1, which maps to index 4 by the formula above (assuming there are four answers). I can always add an additional line of code that takes care of that case separately,

if rangedSlider.value == 1 { index = currentAnswers.count - 1 }

but I prefer a one line solution.

I can also set the max value of the slider to 0.99 in the Storyboard and stick with the first line of code I wrote, but I want to know: is there a built-in way to make the range of UISlider values an open interval? Is there a better way to get the behavior I want?

  • Sorry for being critical, but this is **very** poor UI design. If you want 4 answers to a single question, don't use a `UISlider`! That is *very* confusing for the user. Maybe consider what other's have done: https://stackoverflow.com/questions/29117759/how-to-create-radio-buttons-and-checkbox-in-swift-ios –  Sep 27 '21 at 23:13
  • The app is a personality quiz of the type you’d see on Buzzfeed. The question I’m posing to the user is “how much do you like [insert thing here]?”, and this is most naturally answered with a UISlider. However, since the personality quiz has a set number of outcomes (my quiz has four different outcomes), I need to map the slider’s value to one of the four different outcomes. – Mathew Soto Sep 29 '21 at 00:51

1 Answers1

0

Is this any more complicated than:

let index = Int(rangedSlider.value * Float(currentAnswers.count - 1))

Or have I misunderstood the problem you're having?

That way your index will be returned as a number between 0 and 3 with 0 corresponding to the first answer and 3 corresponding to the fourth answer.

Scott Thompson
  • 22,629
  • 4
  • 32
  • 34
  • This certainly works to map the slider's value to an index without causing a crash, but I want each answer choice to have an equal distribution of slider values. Your solution (assuming there are four answers) gives 1/3 weight to the second and third elements, and 1/6 weight to the first and fourth. I want each answer to get 1/4 of the slider. – Mathew Soto Sep 27 '21 at 18:03