简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM