实现步骤/捕捉UISlider

时间:2011-06-16 10:22:31

标签: iphone uislider

我正在尝试使用UISlider实现某种形式的捕捉或步骤。我写了下面的代码,但它没有像我希望的那样顺利。它可以工作,但是当我向上滑动时,它会向右滑动5个点,手指不会居中于“滑动圆圈”

这是我的代码,其中self.lastQuestionSliderValue是我已设置为滑块初始值的类的属性。

    if (self.questionSlider.value > self.lastQuestionSliderValue) {
        self.questionSlider.value += 5.0;
    } else {
        self.questionSlider.value -= 5.0;
    }

    self.lastQuestionSliderValue = (int)self.questionSlider.value;

6 个答案:

答案 0 :(得分:132)

这实际上比我想象的要容易得多。最初我试图获得正确的属性并做复杂的数学运算。这就是我最终的结果:

h文件:

@property (nonatomic, retain) IBOutlet UISlider* questionSlider;
@property (nonatomic) float lastQuestionStep;
@property (nonatomic) float stepValue;

m文件:

- (void)viewDidLoad {
    [super viewDidLoad];

    // Set the step to whatever you want. Make sure the step value makes sense
    //   when compared to the min/max values for the slider. You could take this
    //   example a step further and instead use a variable for the number of
    //   steps you wanted.
    self.stepValue = 25.0f;

    // Set the initial value to prevent any weird inconsistencies.
    self.lastQuestionStep = (self.questionSlider.value) / self.stepValue;
}

// This is the "valueChanged" method for the UISlider. Hook this up in
//   Interface Builder.
-(IBAction)valueChanged:(id)sender {
    // This determines which "step" the slider should be on. Here we're taking 
    //   the current position of the slider and dividing by the `self.stepValue`
    //   to determine approximately which step we are on. Then we round to get to
    //   find which step we are closest to.
    float newStep = roundf((questionSlider.value) / self.stepValue);

    // Convert "steps" back to the context of the sliders values.
    self.questionSlider.value = newStep * self.stepValue;
}

确保您连接UISlider视图的方法和插座,您应该好好去。

答案 1 :(得分:20)

对我来说最简单的解决方案就是

- (IBAction)sliderValueChanged:(id)sender {
    UISlider *slider = sender;
    slider.value = roundf(slider.value);
}

答案 2 :(得分:7)

也许有人需要! 在我的情况下,我需要任何整数步骤,所以我使用以下代码:

-(void)valueChanged:(id)sender {
    UISlider *slider = sender;
    slider.value = (int)slider.value;
}

答案 3 :(得分:6)

SWIFT VERSION

实施例: 您希望滑块从1-10000开始,步长为100。 UISlider设置如下:

slider.maximumValue = 100
slider.minimumValue = 0
slider.continuous = true

在滑块的动作func()中使用:

var sliderValue:Int = Int(sender.value) * 100

答案 4 :(得分:4)

另一种Swift方法是做类似

的事情
let step: Float = 10
@IBAction func sliderValueChanged(sender: UISlider) {
  let roundedValue = round(sender.value / step) * step
  sender.value = roundedValue
  // Do something else with the value

}

答案 5 :(得分:3)

非常简单:

- (void)sliderUpdated:(UISlider*)sli {
    CGFloat steps = 5;
    sli.value = roundf(sli.value/sli.maximumValue*steps)*sli.maximumValue/steps;    
}

如果你想要一个快速的解决方案并且你已经通过UIControlEventValueChanged添加了目标,那就太棒了。