实施步骤/贴紧UISlider
我正试图用UISlider来实现某种forms的捕捉或步骤。 我已经写了下面的代码,但它不像我所希望的那样顺利。 它可以工作,但是当我向上滑动时,它向右抓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;
这实际上比我想象的要容易得多。 本来我试图得到拇指属性,做复杂的math。 以下是我最后的结果:
h文件:
@property (nonatomic, retain) IBOutlet UISlider* questionSlider; @property (nonatomic) int lastQuestionStep; @property (nonatomic) int 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视图的方法和出口,你应该很好去。
对我来说最简单的解决scheme就是
- (IBAction)sliderValueChanged:(id)sender { UISlider *slider = sender; slider.value = roundf(slider.value); }
也许有人会需要! 在我的情况下,我需要任何整数步骤,所以我使用了下面的代码:
-(void)valueChanged:(id)sender { UISlider *slider = sender; slider.value = (int)slider.value; }
一个非常简单的:
- (void)sliderUpdated:(UISlider*)sli { CGFloat steps = 5; sli.value = roundf(sli.value/sli.maximumValue*steps)*sli.maximumValue/steps; }
太棒了,如果你想要一个快速的解决scheme,并且已经通过UIControlEventValueChanged添加了目标。
SWIFT版本
示例:您需要一个滑块从1-10000步进到100步。UISlider设置如下:
slider.maximumValue = 100 slider.minimumValue = 0 slider.continuous = true
在滑块的动作func()中使用:
var sliderValue:Int = Int(sender.value) * 100
另一个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 }
你可以阅读更多关于我的文章的方法和设置。