实现步骤/捕捉UISlider

问题描述 投票:43回答:6

我正在尝试使用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;
iphone uislider
6个回答
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视图的方法和插座,你应该好好去。


20
投票

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

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

7
投票

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

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

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
投票

另一种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

}

3
投票

一个非常简单的:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.