I successfully created a slider for user height in storyboard and the corresponding code to assign a value in the slider to each level of height but as you can see below, I had to manually copy & paste each new height variable to get it to work. I was curious how an expert would simplify this code? thanks!
*note – I removed the code for height 5’2 to 6’4 to not take up so much space.
”’
@IBOutlet weak var yourHeightEquals: UILabel!
@IBOutlet weak var heightSliderOutlet: UISlider!
@IBAction func heightSliderAction(_ sender: UISlider) {
heightSliderOutlet.value = roundf(heightSliderOutlet.value)
let yourHeightText: String = "Your Height: "
if heightSliderOutlet.value == 0 {
let yourHeightString = "Choose Your Height"
yourHeightEquals.text = yourHeightString
}
else if heightSliderOutlet.value == 1 {
let yourHeightString = "<5'0"
yourHeightEquals.text = yourHeightText + yourHeightString
}
else if heightSliderOutlet.value == 2 {
let yourHeightString = "5'0"
yourHeightEquals.text = yourHeightText + yourHeightString
}
else if heightSliderOutlet.value == 3 {
let yourHeightString = "5'1"
yourHeightEquals.text = yourHeightText + yourHeightString
}
…….
else if heightSliderOutlet.value == 19 {
let yourHeightString = "6'5"
yourHeightEquals.text = yourHeightText + yourHeightString
}
else if heightSliderOutlet.value == 20 {
let yourHeightString = ">6'5"
yourHeightEquals.text = yourHeightText + yourHeightString
}
}
”’
2
Answers
Update - the switch code above only worked for a metric system - I had to modify it a bit for feet & inches, still much cleaner than my original code!
You can use a switch statement like this.