Search code examples
swiftswift3uislider

Using UISlider for updating Strings in a Label rather than a Int/Double etc


Im trying to get a UISlider to give me String values based on its position within the, "slide bar" shall we say.

What I am looking for is if the Int value of the Slider is 1 then the textLabel will be "Daily" as per below:

1 = "Daily"
2 = "Weekly"
3 = "Monthly"
4 = "Quarterly"
5 = "Annually"

I know it would be easier to use the UIPicker but in all honesty it will ruin the design of the app :(

here is my code so far... Note* I have put both the Outlet & Action.

@IBAction func durationAction(_ sender: UISlider) {

    durationLabel.text = "\(Int(durationSlider.value))"

if durationSlider.value == 1
{
    self.durationLabel.text = "Daily"
}
if durationSlider.value == 2
{
    self.durationLabel.text = "Weekly"
}
if durationSlider.value == 3
{
    self.durationLabel.text = "Monthly"
}
if durationSlider.value == 4
{
    self.durationLabel.text = "Quarterly"
}
if durationSlider.value == 5
{
    self.durationLabel.text = "Annually"
}

The above code only gives me the first and last positions. Which clearly means im doing something wrong.

Any help would be greatly appreciated. - Thanks guys.


Solution

  • The values of the slider are Floats. You should round them to the nearest Int before checking. If you put your Strings into an array, you could select them directly.

    @IBAction func durationAction(_ sender: UISlider) {
        let intervals = ["Daily", "Weekly", "Monthly", "Quarterly", "Annually"]
        self.durationLabel.text = intervals[Int(sender.value.rounded()) - 1]
    }