简体   繁体   English

如何在Swift中从UISlider向值添加百分号

[英]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. 我想在快速移动滑块时,将UISlider的值中的百分号添加为UILabel中的字符串。

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. 我希望标签显示25.00%左右,并且随着您移动滑块而变化,但是即使在左右移动滑块后,标签也仅显示0.00%。

val1 is a String created from an Int of the slider's float value. val1是根据滑块的float值的Int创建的String Just get rid of val1 and use the slider's value. 只需摆脱val1并使用滑块的值即可。

@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:) . 注意,最好将NumberFormatternumberFormat.percent一起使用,而不是使用String(format:) This way the value is formatted correctly for the user's locale. 这样,就可以为用户的语言环境正确设置值的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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