Search code examples
iosswiftuislider

How do I add a percent sign to value from UISlider in Swift


I want to add a percent sign to the value from a UISlider as a string in a UILabel as you move the slider around in swift.

Here is what I have already tried.

@IBOutlet weak var label2: UILabel!

@IBAction func slider2(_ sender: UISlider) {
    let val1 = String(Int(sender.value))
    label2.text = String(format: "%.2f%%", val1)
}

I was expecting the label to show something like 25.00% and change as you move the slider, but instead it only shows 0.00% even after moving the slider around.


Solution

  • val1 is a String created from an Int of the slider's float value. Just get rid of val1 and use the slider's value.

    @IBAction func slider2(_ sender: UISlider) {
        label2.text = String(format: "%.2f%%", sender.value)
    }
    

    Note that it would be better to use NumberFormatter with a numberFormat of .percent instead of using String(format:). This way the value is formatted correctly for the user's locale.