如何在Swift中自定义UISlider值 [英] How to customize UISlider Value in Swift

查看:164
本文介绍了如何在Swift中自定义UISlider值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以编程方式创建 UISlider 。我尝试自定义 UISlider 值为4.1,4.2,4.3,4.4,4.5,5.0,5.1,5.2,5.3,5.4,5.5,6.0,...任何人都给我解决方案

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 give me the solution

sliderDemo = UISlider(frame:CGRectMake(0, 0, 200,20))
    var numberOfSteps : NSInteger = numbers.count - 1
    sliderDemo.minimumValue = 6.5
    sliderDemo.maximumValue = 4.1
    sliderDemo.continuous = true
    sliderDemo.value = 4.0
    sliderDemo.addTarget(self, action: "sliderValueDidChange:", forControlEvents: .ValueChanged)
    self.view.addSubview(sliderDemo)

func sliderValueDidChange(sender:UISlider!)
{
    println("number:\(sender.value)")
}


推荐答案

我只是为您创建一个自定义滑块的示例,在这种情况下,我自己创建并将其添加到表单中,但您可以轻松地适应使用故事板中的一个,所有您需要的要做的是将您的值添加到数字数组res ult将在valueChanged函数中的变量号中,您可以使用观察者,通知或协议在更改时检索值,或者只是从那里调用函数。

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
        }
    }
}

我希望能帮到你!

这篇关于如何在Swift中自定义UISlider值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆