How to customize UISlider Value in Swift

后端 未结 1 553
梦谈多话
梦谈多话 2021-01-20 00:09

I create UISlider Programmatically. I try to customise UISlider value as 4.1, 4.2, 4.3, 4.4, 4.5, 5.0, 5.1, 5.2, 5.3, 5.4, 5.5, 6.0, ... Anybody gi

相关标签:
1条回答
  • 2021-01-20 00:43

    I just create an example of a custom slider for you, in this case I am creating and adding it myself to the form but you can easily adapt to use the one from storyboard, all you need to do is to add your values to the numbers array, the result will be in the variable number in the valueChanged function, you can use observer, notifications or protocol to retrieve the value as it change, or simply call a function from there.

    class ViewController: UIViewController {
    
        var slider:UISlider?
        // These number values represent each slider position
        var numbers = [1, 2, 3, 4, 5, 6, 7] //Add your values here
        var oldIndex = 0
    
        override func viewDidLoad() {
            super.viewDidLoad()
            slider = UISlider(frame: self.view.bounds)
            self.view.addSubview(slider!)
    
            // slider values go from 0 to the number of values in your numbers array
            var numberOfSteps = Float(numbers.count - 1)
            slider!.maximumValue = numberOfSteps;
            slider!.minimumValue = 0;
    
            // As the slider moves it will continously call the -valueChanged:
            slider!.continuous = true; // false makes it call only once you let go
            slider!.addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)
        }
        func valueChanged(sender: UISlider) {
            // round the slider position to the nearest index of the numbers array
            var index = (Int)(slider!.value + 0.5);
            slider?.setValue(Float(index), animated: false)
            var number = numbers[index]; // <-- This numeric value you want
            if oldIndex != index{
                println("sliderIndex:\(index)")
                println("number: \(number)")
                oldIndex = index
            }
        }
    }
    

    I hope that helps you!

    0 讨论(0)
提交回复
热议问题