How can I restrict iOS slider value to an integer?

21.8k Views Asked by At

I have a horizontal UISlider to control the volume from 1 to 16 as min and max value, but it's returning float values when I do print().

How can I restrict the UISlider value to an integer?

@IBOutlet var ringValue: UISlider!

@IBAction func ringVolumeSliderChange(_ sender: UISlider)
{
    print(sender.value)
}
8

There are 8 best solutions below

1
On BEST ANSWER
@IBAction func SliderValueChanged(_ sender: UISlider) {
    showValueSlider.text = String(format: "The value is:%i",Int(sender.value))
}
1
On

value property of UISlider is of Float type so you cannot change that but you can convert it to Int using Int(sender.value).

@IBAction func ringVolumeSliderChange(_ sender: UISlider) {
    print(Int(sender.value))
}
0
On

If you want your Slider to position only at the steps do:

@IBAction func ringVolumeSliderChange(_ sender: UISlider)
{
    sender.setValue(sender.value.rounded(.down), animated: true)
    print(sender.value)
}

In this example, I assume you've set min and max values. Now the slider jumps from position to position as the user slides around.

3
On

I have a horizontal UISlider to control the volume from 1 to 16 as min and max value...

By default, the minimum value of value property is 0.0 and the maximum is 1.0.

If you want to get an integer number from 1 to 16 based on the slider value, you should do what @NiravD suggested with extra -pretty simple- maths :)

@IBAction func ringVolumeSliderChange(_ sender: UISlider) {
    print(Int((sender.value * 15).rounded()) + 1)
}

Letting it as print(Int(sender.value)), it prints 1 iff the slider reached its maximum value (1.0), all other values are less that 1.0 will printed as 0.

0
On

To make the slider more smoothly and take one result at a time (when the user stop sliding) you can use this line inside viewDidLoad :

ringValue.isContinuous = false

Then you can choose how you will handle the result from one of the other answers. I liked jboi's answer so it will take discrete values.

1
On

You can try this

@IBOutlet var ringValue: UISlider!

@IBAction func ringVolumeSliderChange(_ sender: UISlider)
{
   print(String(format: "%.0f", sender.value))
}
1
On
var slideValue: String = "0"

@objc private func didSliderValueChanged(_ sender: UISlider) {
    let formattedValue = String(format: "%.0f", sender.value)
    
    if let floatValue = Float(formattedValue) {
        sender.value = floatValue
    }
        
    guard formattedValue != slideValue else {
        return
    }

    //This part is optional, and can make slider more interactive
    UIImpactFeedbackGenerator(style: .medium).impactOccurred()

    slideValue = formattedValue
}
4
On

SwiftUI

@State private var diameter: Double = 10
var body: some View {
     HStack {
       Slider(value: $diameter, in: 0...100)
       Text("\(Int(diameter))")
     } 
}