Implementing steps/snapping UISlider

不想你离开。 提交于 2019-11-29 19:57:40
FreeAsInBeer

It's actually considerably easier than I first thought. Originally I was trying to get the thumbrect property and do complicated math. Here's what I ended up with:

h File:

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

m File:

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

Make sure you hook up the method and the outlet for your UISlider view and you should be good to go.

The simplest solution to me was just

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

Maybe someone will need! In my situation I needed any integer step, so I used the following code:

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

SWIFT VERSION

Example: You want a slider to go from 1-10000 in steps of 100. UISlider setup is as follows:

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

In the action func() for the slider use:

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

Another Swift approach is to do something like

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

}

A really simple one:

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

Great if you want a fast solution and you've added the target by UIControlEventValueChanged.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!