实现步骤/捕捉UISlider [英] Implementing steps/snapping UISlider
问题描述
我正在尝试使用UISlider实现某种形式的捕捉或步骤。我写了下面的代码,但它没有像我希望的那样顺利。它可以正常工作,但是当我向上滑动时,它会向右滑动5个点,手指不会在滑动圆圈上方居中
I am trying to implement some form of snapping or steps with the UISlider. I have written the following code but it does not work as smooth as I hoped for. It works, but when the I slide it upwards it snap 5points to the right leaving the finger not centered over the "slide-circle"
这是我的代码,其中 self.lastQuestionSliderValue
是我设置为滑块初始值的类的属性。
This is my code where self.lastQuestionSliderValue
is a property of the class which I have set to the initial value of the slider.
if (self.questionSlider.value > self.lastQuestionSliderValue) {
self.questionSlider.value += 5.0;
} else {
self.questionSlider.value -= 5.0;
}
self.lastQuestionSliderValue = (int)self.questionSlider.value;
推荐答案
这实际上比我想象的要容易得多。最初我试图获得正确的属性并做复杂的数学运算。以下是我最终的结果:
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文件:
@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视图的方法和插座应该不错。
Make sure you hook up the method and the outlet for your UISlider view and you should be good to go.
这篇关于实现步骤/捕捉UISlider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!