简体   繁体   English

如何将UISlider快速舍入为int

[英]How do you round a UISlider to an int in swift

I was wondering how to round a UISilder value to a int value. 我想知道如何将UISilder值舍入为int值。 Right now it is displaying floats. 现在它正在显示浮动。 I am using swift 3 at the moment. 我目前正在使用swift 3。

     @IBOutlet var slidermove: UISlider!

     @IBAction func SliderVal(_ sender: AnyObject) {

         print(slidermove)
         let x = round(slidermove)
  }

round() does not work it will give an error, thanks for anyone that helps round()不起作用,它将给出一个错误,感谢任何帮助

You should round it's value instead of UISlider itself.: 您应该舍入它的值,而不是UISlider本身。

let x = roundf(slider.value) // x is Float

If you need an Int instead of Float , just wrap it with Int initializer: 如果您需要一个Int而不是Float ,只需用Int初始值设定项将其包装即可:

let x = Int(round(slider.value)) // x is Int

To round a Float to the nearest integer and get the result as an Int , the (perhaps not so well-known) function lrintf() can be used. 要将Float舍入到最接近的整数并以Int获取结果,可以使用函数lrintf() (可能不太知名)。 Example: 例:

let x = Float(12.6)
let i = lrintf(x)
print(i) // 13

In your case: 在您的情况下:

let i = lrintf(slider.value) // `i` is an `Int`

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

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