实现步骤/捕捉UISlider

Luc*_*uke 45 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;
Run Code Online (Sandbox Code Playgroud)

Fre*_*eer 133

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

h文件:

@property (nonatomic, retain) IBOutlet UISlider* questionSlider;
@property (nonatomic) float lastQuestionStep;
@property (nonatomic) float stepValue;
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这很好用.我希望我能给它两个赞成. (8认同)

Ada*_*hns 20

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

- (IBAction)sliderValueChanged:(id)sender {
    UISlider *slider = sender;
    slider.value = roundf(slider.value);
}
Run Code Online (Sandbox Code Playgroud)


rus*_*gun 7

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

-(void)valueChanged:(id)sender {
    UISlider *slider = sender;
    slider.value = (int)slider.value;
}
Run Code Online (Sandbox Code Playgroud)


Jur*_*ure 7

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

}
Run Code Online (Sandbox Code Playgroud)


Pes*_*lly 6

SWIFT VERSION

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

slider.maximumValue = 100
slider.minimumValue = 0
slider.continuous = true
Run Code Online (Sandbox Code Playgroud)

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

var sliderValue:Int = Int(sender.value) * 100
Run Code Online (Sandbox Code Playgroud)